Possible to use attr_reader/writer in model?

I have some properties that I want setable externally, but readable only
internally. I’ve played around with attr_writer (and attr_reader
separately) but can’t figure out how to get either to work. I can do
what I want using attr_accessor, or just straight out defining the prop
setter method. Anybody know how to use attr_writer or attr_reader with a
model?

You da man,
Joe

Hi –

On Sat, 4 Nov 2006, Joe R. MUDCRAP-CE wrote:

I have some properties that I want setable externally, but readable only
internally. I’ve played around with attr_writer (and attr_reader
separately) but can’t figure out how to get either to work. I can do
what I want using attr_accessor, or just straight out defining the prop
setter method. Anybody know how to use attr_writer or attr_reader with a
model?

It should work out of the box. What’s not working?

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

Joe R. MUDCRAP-CE wrote:

I have some properties that I want setable externally, but readable only
internally. I’ve played around with attr_writer (and attr_reader
separately) but can’t figure out how to get either to work. I can do
what I want using attr_accessor, or just straight out defining the prop
setter method. Anybody know how to use attr_writer or attr_reader with a
model?

You da man,
Joe

attr_* methods create public methods for accessing instance varables.
If you dont want the reader method to be puclic, then use attr_writer
only.

class Foo
attr_writer :bar

def bar_is_baz?
@bar == ‘baz’
end
end

foo = Foo.new
foo.bar = ‘snork’
foo.bar #=> Undefined method
foo.bar_is_baz? #=> false
foo.bar = ‘baz’
foo.bar_is_baz? #=> true