From: Alex Young Date: 2007-12-14T18:45:24+09:00 Subject: Re: attr_accessor for question methods (?) Charles Oliver Nutter wrote: > Trans wrote: >> Like to make a small suggestion for 1.9. It would be great if we could >> do: >> >> attr_accessor :foo? >> >> With the effect of: >> >> def foo? >> @foo >> end >> >> def foo=(x) >> @foo=x >> end >> >> This is much nice then having to define one attribute plus a >> supplemental "?" method. attr_reader :foo? would work too, of course. >> While it would be rather meaningless for attr_writer, it could work in >> any case --really no need to raise an error. >> >> A minor detail, but one that would be convenient to have. > > Perhaps an additional method would be the way to do it? > > question_accessor > predicate_accessor > pred_accessor > boolean_accessor > bool_accessor How about a single method that handles all possible accessor methods, rather than a proliferation of attr_*s and *_accessors? attr_set :foo, [:test, :read, :write] There's room in there to make it user-extensible, too, so if I want (for example) a generic attribute method that resets my attribute to nil, I could do (something like): def_attr_setter :nullify, "%s_to_nil", Proc.new{|obj,sym| obj.instance_variable_set("@#{sym}", nil)} then later: attr_set :bar, [:nullify] which would give me something equivalent to this method: def bar_to_nil self.class.__attr_setters__[:nullify].call(:bar) end Thoughts? It's pretty ugly internally the way I've sketched it here, but I kind of like the API... -- Alex