many attributes, same behavior

P

Paul Winward

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
 
J

James Britt

Paul said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top