[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

many attributes, same behavior

Paul Winward

5/2/2008 6:14:00 PM

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
--
Posted via http://www.ruby-....

1 Answer

James Britt

5/2/2008 6:40:00 PM

0

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 Britt

http://www.... - Hacking in the Desert
http://www.jame... - Playing with Better Toys