Created
December 6, 2013 06:41
-
-
Save corysimmons/7819544 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class WrappedObject | |
attr_reader :child | |
def initialize(child, log = nil) | |
@child = child | |
@log = log || [] | |
@new_entry = nil | |
end | |
def record | |
raise "No events to record" unless @new_entry | |
@log << @new_entry | |
@new_entry = nil | |
end | |
def log | |
@log.map do |entry| | |
args = entry[:args].empty? ? '' : '(' << entry[:args].map(&:inspect).join(', ') << ')' | |
"#{entry[:method]}#{args}" | |
end.join('.') | |
end | |
def method_missing(method, *args, &blk) | |
# Only log if this doesn't throw an exception | |
result = @child.public_send(method, *args, &blk) | |
@new_entry = { :method => method, :args => args } | |
WrappedObject.new(result, @log + [@new_entry]) | |
end | |
def inspect | |
@child.inspect | |
end | |
def to_s | |
@child.to_s | |
end | |
end | |
class Object | |
def wrap | |
WrappedObject.new(self) | |
end | |
end | |
foo = "Test".wrap | |
foo.upcase! | |
# No, not quite right | |
foo.downcase! | |
# That's the one! | |
foo.record | |
foo = foo.gsub("t", "p") | |
# These get recorded anyway | |
# Show the log | |
puts foo.log | |
# Show the child | |
p foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment