We use define method to create a method on the fly given a string as a name.
class Adefine_method :c doputs "Hey!"endendA.new.bA.new.c(1,2)
Exercise - Green Hamsters
Hamsters come in red, green, blue and orange.
A hamster class looks like this:
class Hamsterattr_accessor :colourend
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.newhammy.colour = :redhammy.is_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?
class Widgetdef productproduct = Product.find_by_slug(object_slug)if !productproduct = Product.firstendproductenddef poempoem = Poem.find_by_slug(object_slug)if !poempoem = Poem.firstendpoemendend
If you don't want to create a whole Rails instance, you can use a simple scaffold like this:
class Productclass << selfdef find_by_slugreturn "success"endendendclass Poem < Product; end