On Thu, Feb 17, 2011 at 1:17 AM, Tony Arcieri <tony.arcieri / medioh.com> wro=
te:
> 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
> =A0def method
> =A0...
> end
>
> 3) Placing class methods into a module, and extending a class with that:
>
> module ClassMethods
> =A0def method
> =A0...
> 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              #=3D> cm
Foo.new.instance_method  #=3D> im
Foo.new.class_method       #=3D> 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.

--=20
Anurag Priyam
http://about.me/yeban/