Skip to content

Koans AboutProxyObjectProject

James Dabbs edited this page Jun 9, 2015 · 1 revision

The rest of the Koan file is unchanged. See inline comments below.

class Proxy
  attr_reader :messages

  def initialize(target_object)
    @object = target_object
    # This instance variable will store the list of all
    #   messages that this object has received (and then
    #   forwarded - _proxied_ - on to the target object
    @messages = []
  end

  # Every time we call a method not defined on this object,
  #   it makes a call to method missing, which allows us to
  #   handle it there
  # Ex. calling `Proxy.new(...).test(1,2) will end up here
  #   with message_name being `:test` and `args` being `[1,2]`
  def method_missing message_name, *args
    # Note that we tried to call this method
    @messages.push message_name
    # Send the method call on to the stored target object
    @object.send message_name, *args
  end

  def number_of_times_called message
    # We added an entry to @messages each time we called something, so ...
    @messages.count message
  end

  def called? message
    # Could also do @messages.include?(message)
    number_of_times_called(message) > 0
  end
end