From: David Masover Date: 2009-02-09T05:48:23+09:00 Subject: Re: best way to protect class instance variables Mike Gold wrote: > Jes炭s Gabriel y Gal叩n wrote: > >> This could save you from accidental changes, but somebody could always >> do this and trash your frozen array: >> >> irb(main):017:0> class Blah >> irb(main):018:1> @blah = %w{nothing is really safe} >> irb(main):019:1> end >> > > Data from a closure cannot be overwritten in this way, and could qualify > as being "really safe". > But, you've already provided a method for breaking that anyway -- define_method. So, someone could always do: blah = MyClass.blah.dup blah[0] = 5 class << MyClass define_method :blah { blah } end To the original poster, you really want to provide a convention, instead -- using .dup, .freeze, or simply documenting that you shouldn't change that array should be enough, unless people start doing metaprogramming. Once they start metaprogramming, there's really nothing you can do short of running all your code with SAFE. The question you need to ask is, are you trying to protect against truly malicious code? If so, stop using eval, or run it with a high SAFE level and research Ruby sandboxing. Or are you trying to protect against programmer error? If so, provide clear documentation, and make it hard to do by accident -- no one's going to call instance_variable_set on your class by accident.