views:

54

answers:

3

I noticed that the code in the rails framework is using the following convention all over the place:

class SomeClass
  class << self
     def some function
     end
  end
end

rather than

class SomeClass
end

def SomeClass.function
end

and

class SomeClass
  def self.somefunction
  end
end

What is the reason for this design choice? They all seem to accomplish them same thing

+1  A: 

One advantage of the class << self choice is that it allows you to define private class methods easily:

class SomeClass
  class << self
    def a_public_method
      "This is a public class method"
    end

    private
    def a_private_method
      "This is a private class method"
    end
  end
end

Otherwise, you have to use private_class_method, i.e.:

class SomeClass
  def self.a_public_method
    "This is a public class method"
  end

  def self.a_private_method
    "This will be a private class method"
  end
  private_class_method :a_private_method
end
Greg Campbell
Can't that be done with the other forms of creating class methods?
Andrew Grimm
Not using Module#private, which only sets the visibility for subsequently declared instance methods.
Greg Campbell
+1  A: 

They are actually different. The inner class declaration in your first example actually references SomeClass's eigenclass. An eigenclass allows you to define instance specific behaviour to your classes. Therefore somefunction method doesn't actually belong to the class, but to the instances of the class.

As to why it's used, I could see it being useful if you wanted to extend the capabilities of an existing class without polluting it's method namespace.

dalton
+1  A: 

Dave Thomas has a nice metaprogramming screencast series that goes into these advanced topics. I believe episode II talks about class << self. The screencasts can be found at http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming

techiferous