开发者

What is the meaning of method class in the class definition in Ruby?

I'm familiar with function definitions and variable declarations being in class definitions:

public class MyClass {
  public int myvar;
  public void doSomething() {

  }
}

But what does it "mean" in Ruby when a method is actually called in the class definition? This happens amply in Rails, for instance:

class User < ActiveRecord::Base
  has_many :posts
end

What exa开发者_如何转开发ctly does this do (at a lower level than "it adds some methods to the class")? How would I implement such a function (e.g., one that mixes in some additional methods)?


During the definition of a class, the receiver is the class object, and so it's really about the same thing as the more familiar class . method technique of calling a class method.

>> class A
>>   def self.hello
>>     puts 'world'
>>   end
>>   hello
>> end
world
=> nil
>> A.hello
world
=> nil
>> class B < A
>>   hello
>> end
world
=> nil

So, to carry the ClassName.new analogy a bit further, you can call any class method this way. Let's use new as an example:

>> class C
>>   def happy
>>     puts 'new year'
>>   end
>>   new
>> end.happy
new year
=> nil

BTW, don't get confused by the fact that this method is defined in the superclass. Q: What's the difference between your derived class and your superclass instance? Say ActiveRecord::Base? A: Nothing! There is only the one class instance.


ActiveRecord::Base defined the class method has_many. Ruby lets you call superclass class methods during the definition of a subclass.

You can do this yourself, add your own class methods to ActiveRecord::Base or your own class by making a Module you mix in.

A simple example of how to do this yourself:

module MyMixin
  def self.included(base)
    base.extend ClassMethods   # Load class methods
    super
  end
  module ClassMethods
    def hello
      puts "MyMixin says => Hello World"
    end
  end
end
ActiveRecord::Base.send :include, MyMixin

Example use:

class MyRecord < ActiveRecord::Base
  hello
end

firing up Rails you would see this printed to the console:

MyMixin says => Hello World
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜