Part 1 · 1 chapters · ~8 min

The Object Model and Metaprogramming

Objects, classes and singleton classes, method lookup and ancestors, modules as mixins with include, prepend and extend, open classes and refinements, define_method and send, class macros, method_missing, and how Rails' declarative style is built from these pieces.

2

Method lookup and mixins

code
module Auditable
  def self.included(base) = base.extend(ClassMethods)
  module ClassMethods
    def audits(*attrs)                                    # a class macro
      attrs.each do |a|
        define_method("#{a}=") do |v|                     # generate a setter that records changes
          (@audit ||= []) << [a, send(a), v]
          super(v)
        end
      end
    end
  end
end

class Account < ApplicationRecord
  include Auditable
  audits :limit_kobo
end
Account.ancestors.take(4)    # => [Account, Auditable, ApplicationRecord, ...]
RUBY METHOD LOOKUP
how a method call finds its implementation
account objectsingleton classmethods on this one objectclass Accountinstance methodsincluded modulesAuditable, ComparablesuperclassApplicationRecord → ActiveRecord::Basemethod_missinglast resort
swipe the figure sideways, or tap expand for full screen
1/5
the lookup chain
Calling account.balance looks in the object's singleton class, then its class, then modules included into the class (most recent first), then the superclass and its modules, up to BasicObject.
singleton → class → modules → superclassAccount.ancestors shows the chain