Using a Proxy class for debugging
rick : March 6th, 2006
Inspired by Jim Weirich's "10 Things Every Java Programmer Should Know About Ruby":http://onestepback.org/articles/10things/index.html presentation, Courtenay had a wicked thought. What if you could proxy objects for debugging purposes?
class Proxy
attr_reader :messages, :context
delegate :class, :to => :context
delegate :is_a?, :to => :context
def initialize(context)
@context = context
@messages = []
end
private
def method_missing(method, *args, &block)
start = Time.now
@context.send(method, *args, &block)
ensure
@messages << [method, args, block, Time.now - start]
end
end
Let's see this bad boy in action:
>> project-mayhem-2:~/p/mephisto/trunk rick$ script/console
Loading development environment.
>> Article = Proxy.new(Article)
(irb):1: warning: already initialized constant Article
=> #
>> Article.count
=> 52
>> a = Proxy.new(Article.find(:first)) ; nil
=> nil
>> Article.messages
=> [[:count, [], nil, 0.054313], [:allocate, [], nil, 4.1e-05], [:find, [:first], nil, 0.012639]]
>> a.title += ' updated'
=> "SimpleXML and Xpath in Php5 updated"
>> a.messages
=> [[:title, [], nil, 0.006489], [:title=, ["SimpleXML and Xpath in Php5 updated"], nil, 9.5e-05]]
8 Responses to “Using a Proxy class for debugging”
Sorry, comments are closed for this article.
March 6th, 2006 at 02:49 PM how about building this into a super-magic-extra-verbose logger for testing?! Testing user_test.rb:
March 6th, 2006 at 03:18 PM :o only in ruby
March 6th, 2006 at 03:42 PM Seems a lot like Jim's FlexMock, but without assertions. Incidentally, you might want to use BlankSlate to ensure you don't get snagged by any of the regular methods.
March 8th, 2006 at 05:43 AM Hey, the C++ Smart Pointer lives!
May 17th, 2007 at 01:12 AM
Nice
May 17th, 2007 at 03:49 AM
Cool.
May 17th, 2007 at 08:08 AM
Nice!
June 14th, 2007 at 12:50 AM
Sorry :(