Search code examples
rubydslmonkeypatchinginstance-eval

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


Solution

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