From: Robert Dober Date: 2010-10-21T03:53:17+09:00 Subject: Re: [Q] best practice for redefining methods at runtime? On Wed, Oct 20, 2010 at 5:31 PM, Chuck Remes wrote: > Is that reasonable or is there a more idiomatic way of accomplishing this task? Reasonable maybe but it is far from achieving what freeze does, because you still have instance_variable_set and as long as this available I can redefine the accesors, thus you would need to block #instance_variable_set, #define_method for the class but I can still beat that for any given instance by introducing singleton methods.... In other words it is a metaprogramming mess.sub("m","h").gsub("s","l")! Maybe you should reconsider your approach, what about freezing the object but accessing it in a wrapper that rescues the exceptions? This could done via closures, and BasicObject makes the task much easier than it was in 1.8 class Freezer < BasicObject freezee = nil define_method :initialize do | f | freezee = f end define_method :method_missing do | name, *args, &blk | begin freezee.send( name, *args, &blk ) rescue ::RuntimeError => re # Pitty that there is no designated Exception for this BTW raise unless /can't modify frozen/ === re.message end end end a = Freezer.new( "" ) a << "1" puts a a.freeze a << "2" puts a # But a.xxx HTH R. -- There are worse things than having people misunderstand your work. A worse danger is that you will yourself misunderstand your work. -- Paul Graham