Created
January 12, 2010 02:46
-
-
Save ravinggenius/274830 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @reference http://ruby-metaprogramming.rubylearning.com/html/Dog_Step2.html | |
class Dog | |
PHRASES = { | |
:dance => 'is dancing', | |
:poo => 'is a smelly doggy!', | |
:laugh => 'finds this hilarious!' | |
} | |
def initialize name | |
@name = name | |
end | |
def name | |
@name | |
end | |
def can *actions, &blk | |
@actions ||= {} | |
actions.each do |action| | |
@actions[action] = PHRASES[action] if PHRASES.include? action | |
@actions[action] = instance_eval &blk if block_given? | |
end | |
end | |
def method_missing missing_method, *args | |
action = missing_method | |
if @actions.include?(action) || PHRASES.include?(action) | |
verb = @actions.include?(action) ? @actions[action] : "doesn't understand #{action}" | |
verb.start_with?(@name) ? verb : "#{@name} #{verb}" | |
else | |
super | |
end | |
end | |
end | |
lassie, fido, stimpy = %w[ Lassie Fido Stimpy ].collect { |name| Dog.new name } | |
lassie.can :dance, :poo, :laugh | |
fido.can(:poo) { "#{name} is smelly." } | |
stimpy.can :dance | |
stimpy.can(:cry) { "#{name} cried AHHHH" } | |
p lassie.dance | |
p lassie.poo | |
p lassie.laugh | |
puts | |
p fido.dance | |
p fido.poo | |
p fido.laugh | |
puts | |
p stimpy.dance | |
p stimpy.poo | |
p stimpy.laugh | |
p stimpy.cry |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment