From: sur max Date: 2007-02-16T22:22:35+09:00 Subject: Re: class design issues ------=_Part_3098_29370142.1171632151670 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi David, Now this should not be available !! lf1.name << "more stuffs" this should generate error !! ... (i agree it is working) but is name is an attr_reader then the manipulations with "<<" should not be supported, as the case of "=" or it should be ? On 2/16/07, dblack@wobblini.net wrote: > > 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" > > => # > > irb(main):011:0> lf1.name > > => "bla" > > irb(main):012:0> lf1.name = "ddd" > > NoMethodError: undefined method `name=' for # > @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) > > -- sur http://expressica.com ------=_Part_3098_29370142.1171632151670--