Module: Monkey

Defined in:
lib/monkey.rb

Defined Under Namespace

Classes: MethodMissingError, MethodPatchedError, MonkeyError

Class Method Summary collapse

Class Method Details

.patch(object, *methods, &scope) ⇒ Object

Patches object to contain the monkeypatched methods. If a block is passed, the monkeypatches are only active for the duration of the block, and the return value is the return value of the block.

Raises a Monkey::MethodMissingError if a named monkeypatch is not defined.

Monkey.patch(Object, :metaclass) do
  "foo".metaclass # => #<Class:#<String:0x10153caf8>>
end

"foo".metaclass # => NoMethodError


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/monkey.rb', line 46

def self.patch(object, *methods, &scope)
  # if the object is a class or metaclass, monkeypatch the class, otherwise
  # monkeypatch the metaclass of the object
  if object.kind_of?(Class) || object == Kernel
    _patch(object, object, *methods, &scope)
  else
    metaclass = (class << object; self; end)
    klass     = object.class
    
    _patch(metaclass, klass, *methods, &scope)
  end
end

.see(klass, &block) ⇒ Object

Allows you to specify a set of monkey patches that can be applied to a class or module. Pass a block to the method and define methods inside the block as normal, and the methods will be available only inside a Monkey#patch block.

Raises a Monkey::MethodPatchedError if the method already has a monkeypatch registered on klass.

Monkey.see(Object) do
  def metaclass
    (class << self; self; end)
  end
end


24
25
26
27
28
29
30
31
# File 'lib/monkey.rb', line 24

def self.see(klass, &block)
  mod     = Module.new(&block)
  methods = mod.instance_methods(false)
  
  methods.each do |method|
    register_patch(klass, method.to_sym, mod)
  end
end