Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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) ?

like image 984
Mellon Avatar asked Jan 10 '11 09:01

Mellon


1 Answers

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.

like image 107
Aditya Sanghi Avatar answered Sep 23 '22 08:09

Aditya Sanghi