Inject data members to an object

2019-08-17 03:10发布

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

4条回答
相关推荐>>
2楼-- · 2019-08-17 03:28

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

查看更多
ら.Afraid
3楼-- · 2019-08-17 03:37

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-08-17 03:40

You could define:

attr_accessor :complete_name

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

查看更多
Animai°情兽
5楼-- · 2019-08-17 03:42

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

def complete_name
  firstname + ', ' + lastname
end
查看更多
登录 后发表回答