Skip to content

Instantly share code, notes, and snippets.

@aprescott
Created December 1, 2011 09:24
Show Gist options
  • Save aprescott/1415295 to your computer and use it in GitHub Desktop.
Save aprescott/1415295 to your computer and use it in GitHub Desktop.
Monitor an object with delegation.
# BasicObject from
# simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/
class BasicObject
instance_methods.each do |m|
undef_method(m) if m.to_s !~ /^__|^nil\?$|^send$|^object_id$/
end
end
class ObjectMonitor < BasicObject
attr_reader :object
def initialize(object)
@object = object
end
def do_something_on_change
Kernel.puts "changed: #{@old} => #{object.inspect}"
end
def method_missing(symbol, *args, &block)
@old = object.inspect
object.send(symbol, *args, &block)
do_something_on_change
end
def self.[](obj)
new(obj)
end
end
s = ObjectMonitor["something"]
s << " goes here"
s << "oh"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment