# Many attributes, same behavior

**URL:** <https://www.ruby-forum.com/t/many-attributes-same-behavior/136503>\
**Category:** Ruby\
**Created:** [May 2, 2008, 8:13pm UTC](https://www.ruby-forum.com/t/many-attributes-same-behavior/136503 "2008-05-02T20:13:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pozza](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/8e8cbc/32.png) [@pozza](https://www.ruby-forum.com/u/pozza)\
**Post date:** [May 2, 2008, 8:13pm UTC](https://www.ruby-forum.com/t/many-attributes-same-behavior/136503/1 "2008-05-02T20:13:20Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![pozza](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/8e8cbc/32.png) [@pozza](https://www.ruby-forum.com/u/pozza)\
**Post date:** [May 2, 2008, 8:40pm UTC](https://www.ruby-forum.com/t/many-attributes-same-behavior/136503/2 "2008-05-02T20:40:50Z")

</div>

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](http://www.rubyaz.org) - Hacking in the Desert  
[http://www.jamesbritt.com](http://www.jamesbritt.com) - Playing with Better Toys
