How would you manipulate a column's attributes?

Is there a way to do this correctly; here’s my “Person” model:

def name
name.gsub(“Jr.”, “Junior”)
end

I have a “name” column in my database, and I want to replace “Jr.” with
“Junior” every time @person.name is called.

I’m getting a “stack level is too deep” error when I put the above
definition in my model. I figure I could just rename the method to
something like “filtered_name” but is there a more efficient way to do
this?

Is there a way to do this correctly; here’s my “Person” model:

def name
name.gsub(“Jr.”, “Junior”)
end

I have a “name” column in my database, and I want to replace “Jr.”
with
“Junior” every time @person.name is called.

I wouldn’t do this. If you insist on it…

def name
read_attribute(name).to_s.gsub(“Jr.”, “Junior”)
end

The “to_s” will handle cases where name is nil. Or you can rescue
it. nil.gsub raises an error.

Anyway, I wouldn’t do it because other things might use @person.name
and not realize there’s some extra magic going on.

I’d create another method and name it something appropriate…
filered_name, prefered_name, cleansed_name, nice_name, expanded_name,
etc…

Or, create a method that works on any string called say
“expand_abbreviations” and then do

@person.name.expand_abbreviations

-philip

Awesome. Thank you Philip! The @person.name.expand_abbreviations sounds
like a great idea. Thanks so much. I appreciate your kind warning and
your fantastic solution.

On Jul 30, 5:37 pm, Bob S. [email protected]
wrote:

definition in my model. I figure I could just rename the method to
something like “filtered_name” but is there a more efficient way to do
this?

Posted viahttp://www.ruby-forum.com/.

ActiveRecord::Base models can act like a hash here:

Hi Bob,

On Thu, 2009-07-30 at 23:37 +0200, Bob S. wrote:

Is there a way to do this correctly; here’s my “Person” model:

def name
name.gsub(“Jr.”, “Junior”)
end

I have a “name” column in my database, and I want to replace “Jr.” with
“Junior” every time @person.name is called.

Philip’s recommendations are spot on, especially his caution re: ‘other
things might use @person.name’. If you’re only interested in what’s
displayed on the screen, you could also use a helper to do this.

Just a thought.

Bill