×

ruby · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a that writes methods for you.

attr_accessor :name looks like a keyword, but it is an ordinary method call. It runs while Ruby reads the class body, and it writes two methods for you. You can build your own. A class method, written def self.field, belongs to the class itself rather than to each object.

Call your class method inside the class body and it becomes a class macro: one readable line that creates methods, usually with define_method. Rails is full of them, from has_many to validates. Here field writes a reader that falls back to a default value.

class Product
  def self.field(name, default)
    define_method(name) do
      @values.fetch(name, default)
    end
  end
  field :colour, "black"
  field :stock, 0
  def initialize(values)
    @values = values
  end
end
mug = Product.new({ colour: "teal" })
puts "#{mug.colour}, #{mug.stock} in stock"

fetch(name, default) looks up a key and hands back the default when that key is missing.