what does "class << self" mean in Rails? [duplicate]
Possible Duplicates:
class << self idiom in Ruby Can someone please explain class << self to me?
I would like to know what does class << self
statement mean in 开发者_Python百科a model class? And how does the statement inside it differ from those outside from it. For example:
class Post < ActiveRecord::Base
class << self
def search(q)
# search from DB
end
end
def search2(qq)
# search from DB
end
end
What does class << self
mean?
What are the differences between method search(q)
and search2(qq)
?
That is the same as
class Post < ActiveRecord::Base
def self.search(q)
# Class Level Method
# search from DB
end
def search2(qq)
# Instance Level Method
# search from DB
end
end
Class methods work on the class (e.g. Post), instance methods works on instances of that class (e.g. Post.new)
Some people like the class << self; code; end;
way because it keeps all class level methods in a nice block and in one place.
Others like to prefix each method with self.
to explicitly know that is a class method not an instance method. It's a matter of style and how you code. If you put all class methods in a block like class << self
, and this block is long enough, the class << self
line might be out of your editor view making it difficult to know that you are in the class instance block.
On the other hand, prefixing each method with self.
and intermixing those with instance methods is also a bad idea, how do you know all the class methods while reading your code.
Pick an idiom which you prefer for your own code base but if you work on an open source project or you collaborate on someone else's code, use their code formatting rule.
It creates class methods as opposed to instance methods. It's the same as doing def self.search(q)
. Those two methods would be called like:
Post.search(q)
Post.new.search(qq)
search2
is an instance-method while search
is a class-method. The class << self
syntax enables you to group class methods below. There are three ways of defining class methods in Ruby:
class MyClass
def self.method
# do sth.
end
def MyClass.method2
# do sth.
end
class << self
def method3
# do sth.
end
def another_class_method
# do sth.
end
end
end
Class-methods are called on a class, not on an instance. It is personal preference which of the three idioms you want to use. I prefer def self.method
for no particular reason.
精彩评论