ruby · level 3 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
When does a class macro run? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Report
def self.column(name)
puts "Adding column #{name}"
define_method("#{name}_label") { name.to_s.capitalize }
end
column :price
column :stock
end
puts "Class ready"
puts Report.new.price_label
your turn
Your turn. Give accounts a flag macro.
Add a flag of your own, such as verified, in the first blank. Then ask Sam about that flag in the second blank.
fix it
The class falls over while it is being read. Fix the macro.
- The error says the class Product has no method
field. Who isselfinside a class body? - Inside the class body,
selfis the class, so the macro must be a class method. - Change line 2 to
def self.field(name, default), then press run.
nailed it
you wrote your own class macros. :D
def self.namemakes a class method.- A class macro runs while Ruby reads the class body.
- Macros use
define_methodto write methods for you.
new words in your collection
- class method
- class macro
This lesson isn’t saved. A free account remembers every lesson you finish.