From: Mike Sassak Date: 2009-07-01T01:18:31+09:00 Subject: Re: attr_writers within blocks --0016e6476e76360af0046d9328d7 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Hi David, On Tue, Jun 30, 2009 at 8:01 AM, David A. Black wrote: > Hi -- > > On Tue, 30 Jun 2009, Mike Sassak wrote: > > On Mon, Jun 29, 2009 at 2:44 PM, Wijnand Wiersma >> 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. > Of course! I was thinking of ActiveRecord's macro method syntax--not the most apropos when the original question was about variable assignment, I know. :-) > > 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 > Ahh, yes. Thanks for pointing that out. I was really more concerned at the time with giving an (admittedly idiosyncratic) example of assignment without an explicit receiver as food for the OP's thought. I'd never thought to use @bar, = v in order to grab only the first element of an array though. Cool! Thanks again, Mike > > > 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 > > --0016e6476e76360af0046d9328d7--