Forum: Ruby on Rails Augmenting to_s for ActiveRecord

Posted by John H. (john_h61)
on 2012-09-03 18:28
(Received via mailing list)
So, I have a model, and I've defined some non-persisted attributes. I'd
like to augment the to_s to include these in to_s and other output
statements (like whatever awesome print is calling).

If possible, I'd like to augment the existing functionality (vs 
replacing
it)?  Is there a standard way to do this?  I can probably figure out how 
to
do this if someone could point me to where to_s is being defined in
ActiveRecord.

Thanks,
Posted by Colin Law (Guest)
on 2012-09-03 18:43
(Received via mailing list)
On 3 September 2012 17:27, John Hinnegan <john.hinnegan@gmail.com> 
wrote:
> So, I have a model, and I've defined some non-persisted attributes. I'd like
> to augment the to_s to include these in to_s and other output statements
> (like whatever awesome print is calling).

What is it that you want to call to_s on?  An instance of the model or
the attribute itself?  If the attribute then what class it is?  If the
model instance then just define to_s in your model class to do
whatever you want.

Colin
Posted by John H. (john_h61)
on 2012-09-03 21:40
(Received via mailing list)
The model itself.

So right now when you inspect, puts, etc on the model, it shows only the
attributes which are persistent. I would like to augment it to also show 
my
non-persisted attributes. This is for debugging purposes only.

I'm guessing somewhere in ActiveModel or ActiveRecord, the to_s is being
overridden. Is there a general way I can override so that to_s, inspect,
and awesome_print will all show the non-persisted attributes?
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.