Many attributes, same behavior

I have a growing list of readable attributes that all essentially do the
same thing – read the requested value from a file. Likewise, the
writable attributes write the associated value to the file.

For the readable attributes, e.g., if the file contains
STATE error
PID 12452

and the file manager object “mngr”, then
mngr.state
mngr.pid

would yield
error
12452

It is becoming cumbersome to have to specify each attribute for the
growing list. One way of dealing with this is to simply have a method,
that takes in the name, like

get(“STATE”)
get(“PID”)

With this approach, there must be a code check to verify the name is
valid (especially when writing a value to a file).

I’m wondering if there’s an interpreter-checked method of doing this.
I’d like to something like:

attr_reader :state, :error {|var| # get value of var from file}, or
attr_writer :state, :error {|var, value| # write “VAR value” in file }

I realize this isn’t possible, but are there any elegant solutions to
accomplish the same behavior?

Thanks!
Paul

Paul Winward wrote:

I’m wondering if there’s an interpreter-checked method of doing this.
I’d like to something like:

attr_reader :state, :error {|var| # get value of var from file}, or
attr_writer :state, :error {|var, value| # write “VAR value” in file }

I realize this isn’t possible, but are there any elegant solutions to
accomplish the same behavior?

Have you tried writing your own versions of attr_reader and attr_writer?

“attributes” are simply methods; the built-in attr_* methods dynamically
create them for you class instances, and this is something you can do
yourself by adding a class method to your class.


James B.

http://www.rubyaz.org - Hacking in the Desert
http://www.jamesbritt.com - Playing with Better Toys

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs