Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Temporarily overriding class methods in Ruby (See related posts)

By Tobi / xal from IRC, and seemingly related to this.

class Object
  def mock_methods(mock_methods)
 
    original = self
 
    klass = Class.new(self) do
 
      instance_eval do       
        mock_methods.each do |method, proc| 
          define_method("mocked_#{method}", &proc)
          alias_method method, "mocked_#{method}"
        end            
      end
 
    end
 
    begin
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, klass)
 
      yield
 
    ensure
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, original)
    end
 
  end
end
 
class Duck
  def quak; puts "Quak";  end
end
 
Duck.new.quak #=> "Quak"
 
Duck.mock_methods(:quak => Proc.new { puts 'Wuff' }) do  
  Duck.new.quak #=> "Wuff"
end

Comments on this post

floehopper posts on Aug 26, 2006 at 14:28
You could use Mocha to do stuff like this.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts