Override to_string for single attribute?

I have a model where I want to change the display for a single attribute
such that if the value is an integer, it displays with no decimal point
(e.g. “1”), but if it is non-integer, it displays with a decimal point
(e.g. “1.25”).

The easiest way to do this seems to be if I could override the to_string
method for my_model.my_attribute.to_s. Is there a way to do this? Or
a better way altogether?

thanks,
Jeff

On Friday, July 14, 2006, at 9:46 PM, Jeff C. wrote:

Jeff


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

override the attribute method on your model and have it return the
formatted value.

_Kevin

How do you do that without making it recursive? For example

#override method for attribute foo
def foo
return format(foo)
end

-jeff

override the attribute method on your model and have it return the
formatted value.

_Kevin

Jeff C. wrote:

override the attribute method on your model and have it return the
formatted value.

_Kevin

How do you do that without making it recursive? For example

#override method for attribute foo
def foo
return format(foo)
end

-jeff

You can use read_attribute for this.

eg the example from the documentation:

class Song < ActiveRecord::Base
# Uses an integer of seconds to hold the length of the song

 def length=(minutes)
   write_attribute(:length, minutes * 60)
 end

 def length
   read_attribute(:length) / 60
 end

end

under ‘Overwriting default accessors’

hth