Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created May 8, 2014 11:50
Show Gist options
  • Select an option

  • Save ifyouseewendy/8a5ef5c2f7ef6c4b2e07 to your computer and use it in GitHub Desktop.

Select an option

Save ifyouseewendy/8a5ef5c2f7ef6c4b2e07 to your computer and use it in GitHub Desktop.
Use a class whose sole responsibility is to handle the method_missing cases.
# Despite the added complexity, method_missing is a powerful tool that needs to be used when the interface of a class cannot be predetermined.
# Use Isolate Dynamic Receptor to move the method_missing behavior to a new class: a class whose sole responsibility is to handle the method_missing cases.
class MessageCollector
instance_methods.each do |meth|
undef_method meth unless meth =~ /^(__|inspect)/
end
def messages
@messages ||= []
end
def method_missing(sym, *args)
messages << [sym, args]
self
end
end
class Recorder
def record
@message_collector ||= MessageCollector.new
end
def play_for(obj)
@message_collector.messages.reduce(obj) do |result, message|
result.send message.first, *message.last
result
end
end
def to_s
@message_collector.messages.reduce([]) do |result, message|
result << "#{message.first}(args: #{message.last.inspect})"
end.join('.')
end
end
class CommandCenter
def start(s); puts s; end
def stop(s); puts s; end
end
recorder = Recorder.new
recorder.record.start('LLLLLL')
recorder.record.stop('RRRRRR')
recorder.play_for(CommandCenter.new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment