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”

  1. court3nay Says:
    how about building this into a super-magic-extra-verbose logger for testing?! Testing user_test.rb:
    
    User#find(1)    122ms
    user#destroy    225ms
    user.reload     223ms
    ====================
    total           570ms  PASS
    
    
  2. Joe Auricchio Says:
    :o only in ruby
  3. Danno Says:
    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.
  4. rickbradley Says:
    Hey, the C++ Smart Pointer lives!
  5. Ivan Says:

    Nice

  6. Nicolaon Says:

    Cool.

  7. Thaddaios Says:

    Nice!

  8. Sotirios Says:

    Sorry :(

Sorry, comments are closed for this article.