Created
December 1, 2011 09:24
-
-
Save aprescott/1415295 to your computer and use it in GitHub Desktop.
Monitor an object with delegation.
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
# 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