DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Temporarily Overriding Class Methods In Ruby

04.09.2006
| 5501 views |
  • submit to reddit
        By Tobi / xal from IRC, and seemingly related to <a href="http://project.ioni.st/post/692#post-692">this.</a>

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

Snippets Manager replied on Fri, 2006/08/25 - 9:09pm

You could use Mocha to do stuff like this.