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

About this user

Peter Cooperx http://www.petercooper.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Temporarily overriding class methods in Ruby

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
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS