Hi -- On Fri, 16 Feb 2007, Robert Klemme wrote: > On 16.02.2007 13:51, Spitfire wrote: >> I have a class which takes an input and produces an object. Let's say, it >> takes inputs about specifications of a life-form, and then creates it >> (instantiates say an object, 'LifeForm'). Let's call this factory class >> 'Creator'. Now, my problem is how do I ensure that once 'Creator' returns a >> 'LifeForm', any external/requestor class can only view the properties of >> LifeForm, that were set during creation, and not be able to modify them??? >> How do I design these imaginary classes 'Creator' and 'LifeForm'? > > First, it is very hard to actually prevent changes of instance variables (if > it is possible at all). For your purposes it is probably sufficient to > define attribute readers only. Second, you do not necessarily need a second > class - basically LifeForm is the factory for LifeForm instances. So you > could do > > class LifeForm > attr_reader :age, :name, :foo > > def initialize(age,name,foo) > @age = age > @name = name > @foo = foo > end > end > > irb(main):010:0> lf1 = LifeForm.new 10, "bla", "buzz" > => #<LifeForm:0x7ef6f5e4 @name="bla", @foo="buzz", @age=10> > irb(main):011:0> lf1.name > => "bla" > irb(main):012:0> lf1.name = "ddd" > NoMethodError: undefined method `name=' for #<LifeForm:0x7ef6f5e4 > @name="bla", @foo="buzz", @age=10> > from (irb):12 > from :0 It does raise the danger of: lf1.name << "more stuff" so it might be good to dup or freeze the mutable ones (though of course someone who really wants to can always pry in with instance_eval). David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)