We use define method to create a method on the fly given a string as a name.
define_method :c do
Exercise - Green Hamsters
Hamsters come in red, green, blue and orange.
A hamster class looks like this:
for now we’ll just assume that only these colours are allowed.
Given an instance of hamster, I would like to be able to call something like:
hammy = Hamster.new
hammy.colour = :red
and have it return true or false
Rather than defining a limited set of methods in advance, use method_missing to catch when a method is not defined, then define it on the fly. If I call is_taupe? method_missing should catch that, define a Hanster#is_taupe? method, then call it.
Exercise - drying up code
The following real code is full of duplication. How might you use define_method to dry it up?
product = Product.find_by_slug(object_slug)
product = Product.first
poem = Poem.find_by_slug(object_slug)
poem = Poem.first
If you don’t want to create a whole Rails instance, you can use a simple scaffold like this:
class << self
class Poem < Product; end