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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With