From: Mike Austin Date: 2006-03-10T18:23:46+09:00 Subject: Re: Having a block executed in the context of an instance Well I found out either way I go with passing a block to Button.new(), it doesn't work very well because subclasses' initialize() is called afterwards and clobbers the changes :) So I just have another method called init(). .... def init() yield self return self end .... button = Button.new.init do |b| b.caption = 'Click Me!' end Mike ara.t.howard@noaa.gov wrote: > On Wed, 8 Mar 2006, Mike Austin wrote: > >> I'm writing a property driven ui and would like to do things like: >> >> button = Button.new do >> caption = 'Click Me' >> end >> >> I've read that 2.0 will have this feature, i.e. Class.new will execute >> it's block argument in it's own context. But how do I do it in 1.8? >> >> Thanks much, >> Mike > > class Button > def initialize(*args, &block) > instance_eval &block > end > end > > note that you'll need to do > > self.caption = 'Click Me' > > or else caption will be a local variable. for an elegant work around > see the > metakoan quiz or my traits library. with it a really nice syntax like > this is > possible > > button = Button.new { > caption 'Click Me' > colour 'Orange' > size '42' > } > > here's a real example from something i'm coding now: > > > class Flo5 < NRT::OLSSubscription::Geotiffed > mode "production" > > roi 47,16,39,27 > > satellites %w( F15 F16 ) > > extensions %w( OIS ) > > solarelevations -180, -12, 10.0 > > hold 0 > > username "flo" > > password "xxx" > > orbital_start_direction "descending" > > start_time "2004-12-08" > end_time "2006-12-08" > > to_keep [ %r/.tif$/, %r/.hdr$/ ] > > tmpwatch "8 days" > end > > > hth. > > > -a >