Inject data members to an object

2019-08-17 02:52发布

问题:

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

回答1:

I think the best way to do this is creation of complete_name attribute in your Person class:

def complete_name
  firstname + ', ' + lastname
end


回答2:

If you are going to be iterating over a lot of records, then using an interpolated string will be more memory-efficient.

def complete_name
  "#{firstname}, #{lastname}"
end

Using String#+ to concatenate strings creates String objects at each step. In other words, if firstname is 'John' and lastname 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.



回答3:

You could define:

attr_accessor :complete_name

in the person model and then just do person.complete_name= person.firstname + ', ' + person.lastname



回答4:

Also, another quick note. You don't need that return statement in Ruby. The last statement in your method will be returned.