Search code examples
rubyselfclass-eval

Explicit use of `self` in method name in class definition


This code is from the Rails Crash Course book:

class Accessor
  def self.accessor(attr)
    class_eval "
      def #{attr}
        @#{attr}
      end

      def #{attr}=(val)
        @#{attr} = val
      end
    "
  end
end

The idea is that a subclass of Accessor can create getter and setter methods by calling the accessor method with the attribute name for which we wish to generate getter and setter methods:

class Element < Accessor
  accessor :name
...

But, why the use of self in def self.accessor(attr)?


Solution

  • Because you want to define accessors for all instances of a class; you don't want to define them for certain instances and not define them for other instances. Hence, defining accessors is something you want to do against a class, not an instance; thus accessor has to be a class method, not an instance method. It will be called in the class body when used.