From: Anurag Priyam Date: 2011-02-17T06:37:50+09:00 Subject: Re: Defining class methods On Thu, Feb 17, 2011 at 1:17 AM, 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 use all three, depending on the situation. Generally, I use method 2 (class << self), but if I have an idea that I will be needing only one, or two class methods (like Module.included) I use method 1 (def self.foo). If it makes sense to separate the class methods from the core definition of a class (like helper/utility functions), I define them in a module in a separate file. I do not find class << self to be ugly and confusing :). I picked up the following pattern going through DataMapper's code (or, was it Ruby Best Practices?). module Foo def instance_method; puts "im"; end module ClassMethods def class_method1; puts "cm" end end def self.included(klass) klass.extend(ClassMethods) end end class Moo include Foo end Foo.class_method #=> cm Foo.new.instance_method #=> im Foo.new.class_method #=> NoMethodError A use case of this pattern for me was defining a Helper module for Sinatra (modular) app where some helpers will be used in the request-response context, while some in the context of the class that inherits from Sinatra::Base. -- Anurag Priyam http://about.me/yeban/