Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey patching built-in ruby classes in limited scopes

I'm working on an internal Ruby DSL and to make it look as pretty as possible I need to monkey patch the Symbol class and add some operators. I want to be responsible in how I do this and would like to limit the scope and lifetime of the patches to a specific block of code. Is there a standard pattern for doing this? Here's some pseudo-code to show what I'm thinking:

class SomeContext
  def self.monkey_patch_region(&block)
    context = SomeContext.new
    context.monkey_patch_Symbol
    context.instance_eval(&block)
    context.unmonkey_patch_Symbol
  end

  # magical method
  def monkey_patch_Symbol
    #...
  end

  # another magical method
  def unmonkey_patch_Symbol
    #...
  end

end

like image 622
David K. Avatar asked Aug 12 '12 07:08

David K.


2 Answers

I believe, that you're looking for ruby refinements. The feature has landed in ruby trunk, but it might be reverted before 2.0

like image 112
Farcaller Avatar answered Oct 18 '22 03:10

Farcaller


I've heard about mixology gem. It was designed to mixin and unmix modules. Maybe it can be useful to monkey and unmonkey patches.

UPDATE: mixology won't help you, as it (un)mixes modules to objects (as with extend), not to classes (as with include), and you want monkey/unmonkey core classes, not their objects individually. Anyway I intend to maintain this answer as possibly useful reference for someone else.

like image 30
Sony Santos Avatar answered Oct 18 '22 04:10

Sony Santos