DZone 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

Garry has posted 5 posts at DZone. View Full User Profile

Temporary Execution Context With Included Modules

08.30.2006
| 4141 views |
  • submit to reddit
        I needed to extend "self" with a module but only wanted the included methods to stick around "temporarily". After a lot of futile attempts with binding, callcc, eval, etc... I found it was as simple as "self.dup.instance_eval { ... } ":

def foo
  'bar'
end

module M
  def foo
    'baz'
  end
end

puts "should be 'bar': #{foo}"

self.dup.instance_eval do
  extend(M)
  puts "should be 'baz': #{foo}"
end

puts "should be 'bar': #{foo}"
    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:26pm

yes, i feel like this is what i've been always missing

Snippets Manager replied on Thu, 2006/03/09 - 7:17am

this is awesome, I have always wanted to do this!