From: "Mauricio Fernández" Date: 2004-01-14T17:15:58+09:00 Subject: Re: What object-configuration approach to use? On Wed, Jan 14, 2004 at 02:07:43PM +0900, Gavin Sinclair wrote: > > 4. YieldSelf > > > > I've seen some people include a "yield self" in the initialize() method, > > which allows you to do something like this: > > > > class Link > > attr_accessor :url, :content, ... # this line was missing > > def initialize(url, content) > > @url = url > > @content = content > > yield self if block_given? > > end > > end > > > > link = Link.new(url, "here") { |l| > > l.title = "the whole story" > > } > > The only downside is that it requires you to set *accessors* instead of > the more restrictive *readers*. Credits go to Hal Fulton batsman@tux-chan:/tmp$ expand -t2 a.rb class A attr_reader :foo, :bar # only for initialize! :nodoc: or something for rdoc attr_writer :foo, :bar def initialize yield self klass = class << self; self end ["foo=", "bar="].each { |m| klass.send :undef_method, m } self end end a = A.new do |s| s.foo = 1 s.bar = 2 end p a a.foo = 1 batsman@tux-chan:/tmp$ ruby a.rb # a.rb:22: undefined method `foo=' for # (NoMethodError) -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com It's computer hardware, of course it's worth having -- Espy on #Debian