Skip to content

Instantly share code, notes, and snippets.

@ravinggenius
Created January 12, 2010 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravinggenius/274830 to your computer and use it in GitHub Desktop.
Save ravinggenius/274830 to your computer and use it in GitHub Desktop.
# @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