Created
July 17, 2015 04:32
-
-
Save shinsyotta/1cd24eee758d84d20398 to your computer and use it in GitHub Desktop.
Seinfeld-based Ruby delegation and dynamic method definitions
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
# The Class | |
class CastMember | |
# The Delegate Method | |
def get_mad_at(target) | |
puts "#{name}: What do you think you're doing, #{target.name}?" | |
target.make_target_of self | |
end | |
# The Output | |
def make_target_of(aggressor) | |
puts "#{name}: #{catchphrase(aggressor)}" | |
end | |
# The Dynamic Method Definition | |
def initialize(name, &block) | |
@name = name | |
define_singleton_method(:catchphrase) do |aggressor, &block| | |
yield(aggressor) | |
end | |
end | |
# The Getter | |
def name | |
@name | |
end | |
# The Setter | |
def name=(name) | |
@name=name | |
end | |
end | |
# The Setup | |
jerry = CastMember.new "Jerry" do |aggressor| | |
"What is the deal with that #{aggressor.name}?" | |
end | |
newman = CastMember.new "Newman" do |aggressor| | |
"Never mess with the post office, #{aggressor.name}!" | |
end | |
george = CastMember.new "Costanza" do |aggressor| | |
"I'm on the edge, #{aggressor.name}!" | |
end | |
kramer = CastMember.new "Kramer" do |aggressor| | |
"#{aggressor.name}, #{aggressor.name}, #{aggressor.name}!!!" | |
end | |
elaine = CastMember.new "Elaine" do |aggressor| | |
"(Pushes #{aggressor.name} in the chest.)" | |
end | |
# The Drama | |
kramer.get_mad_at jerry | |
elaine.get_mad_at george | |
jerry.get_mad_at newman |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jerry.send :define_singleton_method, :joke do |topic|
puts "What is the deal with #{topic}?"
end