From: Sean O'Halpin Date: 2011-02-18T02:49:31+09:00 Subject: Re: Defining class methods On Wed, Feb 16, 2011 at 7:47 PM, Tony Arcieri wrote: > It seems there are 3 ways of defining class methods (at least in common > usage): > > 1) Defining a method on self: > > def self.method > > 2) Opening up self and defining the methods directly: > > class << self >  def method >  ... > end > > 3) Placing class methods into a module, and extending a class with that: > > module ClassMethods >  def method >  ... > end > > extend ClassMethods > > -- > > Which of these do you use and which do you prefer? Do you use all three? Do > you think class << self is fugly and confusing? > > I used to use class << self quite frequently and have been shifting to using > modules when dealing with a large number of class methods. I can't really > say I'm a huge fan. > > -- > Tony Arcieri > Medioh! Kudelski > It depends on whether and how you want to allow methods to be overridden. Using #extend and 'def self.xxx' are not the same, viz: module A def run puts "A" end end class Foo extend A end class Bar extend A end Foo.run # => "A" Bar.run # => "A" module B def run puts "B" end end class Foo def self.run puts "foo" end end Foo.extend(B) Bar.extend(B) Foo.run # => "foo" - extend does not override a def self.method Bar.run # => "B" - but it does override a previously defined extension class Foo class << self def run puts "bar" end end end Foo.run # => "bar" - using 'class << self; def method' ... same as 'def self.method' Personally, I've come to prefer using #extend. Regards, Sean