This question is based on another question of mine(thankfully answered).
So if in a model I have this:
def self.find_extended
person = Person.find(:first)
complete_name = person.firstname + ', ' + person.lastname
return person
end
How can I inject complete name in the person object so in my controller/view I can access it by person.complete_name?
Thank you for your time,
Silviu
Also, another quick note. You don't need that return statement in Ruby. The last statement in your method will be returned.
If you are going to be iterating over a lot of records, then using an interpolated string will be more memory-efficient.
Using
String#+
to concatenate strings creates String objects at each step. In other words, iffirstname
is'John'
andlastname
is'Doe'
, then each of these strings will exist in memory and need to be garbage-collected at some point:'John'
,'Doe'
,'John, '
, and finally'John, Doe'
. Not to mention that there are three method invocations instead of one string interpolation which is more efficiently implemented in C.If you use the
#{}
notation, then you avoid creating the'John, '
string. Doesn't matter when dealing with one or two records, but in large datasets used in all sorts of methods it can add up quickly.You could define:
in the person model and then just do
person.complete_name= person.firstname + ', ' + person.lastname
I think the best way to do this is creation of complete_name attribute in your Person class: