Hi --

On Tue, 30 Jun 2009, Mike Sassak wrote:

> On Mon, Jun 29, 2009 at 2:44 PM, Wijnand Wiersma <wijnand / videre.net> wrote:
>
>> Hi all,
>>
>> It seems writer methods don't work within blocks, the names are resolved to
>> new local variable names I guess.
>> It is funny however the reader method does seem to work fine.
>> Is it possible to make it work anyway  without changing the syntax within
>> the block?
>>
>> My example gist: http://gist.github.com/137741
>>
>
> You can override the getter method for a DSL-ish syntax:

Assuming your DSL depends on the lack of equal-signs :-) There's
nothing inherent in the concept of a DSL that disallows =-terminated
methods or explicit receivers.

> class Foo
>  attr_accessor :bar

No point defining #bar if you don't want it -- just use attr_writer.

>  def initialize(&block)
>    instance_eval(&block)
>  end
>
>  def bar(v=nil)
>    v ? @bar = v : @bar
>  end

That won't allow you to (re)set @bar to nil or false, though. You
might want something like:

   def bar(*v)
     unless v.empty?
       @bar, = v
     end
     @bar
   end


David

-- 
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
"Ruby 1.9: What You Need To Know" Envycasts with David A. Black
http://www.envycasts.com