Monkey patching built-in ruby classes in limited scopes

Viewed 356

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

2 Answers
Related