Skip to content

Instantly share code, notes, and snippets.

@jedp
Last active August 29, 2015 14:05
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 jedp/7ef84e6141b5828d6564 to your computer and use it in GitHub Desktop.
Save jedp/7ef84e6141b5828d6564 to your computer and use it in GitHub Desktop.
Create a proxy object class
# Answer to a ruby koan:
# http://koans.heroku.com/en/about_proxy_object_project
# Project: Create a Proxy Class
#
# In this assignment, create a proxy class (one is started for you
# below). You should be able to initialize the proxy object with any
# object. Any messages sent to the proxy object should be forwarded
# to the target object. As each message is sent, the proxy should
# record the name of the method send.
#
# The proxy class is started for you. You will need to add a method
# missing handler and any other supporting methods. The specification
# of the Proxy class is given in the AboutProxyObjectProject koan.
class Proxy
def initialize(object)
@object = object
# keep track of objects called on the proxied object,
# and how many times each was called
@messages = {}
end
def method_missing(name, *args, &block)
if @object.respond_to? name
@messages[name] = (@messages[name] || 0) + 1
@object.send(name, *args, &block)
else
super(name, *args, &block)
end
end
def called?(name)
@messages.include? name
end
def number_of_times_called name
@messages[name] || 0
end
def messages
@messages.keys
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment