Kaplan Ilya
Kaplan Ilya

Reputation: 693

"class<<self" vs "extend ClassMethods"

2 main techniques for creating class methods (without the obvious "def self.method") are:

  1. Defining them in "class << self" block
  2. Defining ClassMethod module and extending it later

I personally prefer second way, seems cleaner. Does anyone has any reason to prefer one technique over the other?

There's also "class_method" method, but I never used it, it has quite complex implementation and seem to do a lot more than previous 2.

Upvotes: 4

Views: 1653

Answers (2)

fylooi
fylooi

Reputation: 3870

self.method is the simplest option when you just need to create one method without dependencies or related logic.

class << self allows you to do far more than define methods on the metaclass. This is useful when you're defining methods which need to work with other parts of the metaclass (eg. aliasing existing method names).

For instance:

class Logger
  class << self
    attr_reader :payload

    def log(message)
      @payload = message
    end
  end
end

The module extension method comes in handy for method reuse and to group multiple coherent methods.

For instance:

module QueryMethods
  def find
  end

  def where
  end
end

module FactoryMethods
  def build
  end

  def create
  end
end

class BusinessModel
  extend QueryMethods
  extend FactoryMethods
end

Upvotes: 5

Vishwas Nahar
Vishwas Nahar

Reputation: 418

First, the class << foo syntax opens up foo's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.

a = 'foo'
class << a
  def inspect
    '"bar"'
  end
end
a.inspect   # => "bar"

a = 'foo'   # new object, new singleton class
a.inspect   # => "foo"

class << self opens up self's singleton class, so that methods can be redefined for the current self object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods

class << self is good at keeping all of your class methods in the same block. If methods are being added in def self.method from then there's no guarantee (other than convention and wishful thinking) that there won't be an extra class method tucked away later in the file.

def self.method is good at explicitly stating that a method is a class method, whereas with class << self you have to go and find the container yourself.

Which of these is more important to you is a subjective decision, and also depends on things like how many other people are working on the code and what their preferences are.

Pros of “class << self” style

Upvotes: 1

Related Questions