2
votes

For a User model with columns :first_name and :last_name, what is the best way to write the full_name method. Both seem to work.

class User < ActiveRecord::Base

    def full_name
       first_name + last_name
    end

end

Or

class User < ActiveRecord::Base

    def full_name
       self.first_name + self.last_name
    end

end

I've looked at the SO posts below but am not sure

Why isn't self always needed in ruby / rails / activerecord?

This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state "parent = value" Ruby assumes you want to assign the value to the local variable parent.

Somewhere up the stack there's a setter method "def parent=" and to call that you must use "self.parent = " to tell ruby that you actually want to call a setter and not just set a local variable.

When it comes to getters Ruby looks to see if there's a local variable first and if can't find it then it tries to find a method with the same name which is why your getter method works without "self".

In other words it's not the fault of Rails, but it's how Ruby works inherently."

Why isn't self always needed in ruby / rails / activerecord?

Why use “self” to access ActiveRecord/Rails model properties?

"Often the use of self is to force Ruby to recognize that as a method call and not mis-interpret it as a variable. Without prior knowledge of a method called day=, then day = "x" looks to Ruby like a variable assignment. self.day = "x" is always a method call.

The reason this is trouble is because the name and name= methods are added dynamically after the User class file has been parsed. The first thing Rails does when using a model is make methods for the associated database fields, but this happens after your user.rb file is parsed."

Why use "self" to access ActiveRecord/Rails model properties?

1
If you are thinking that the reason the first way works is because they are interpreted as local variables, then you are entirely wrong.sawa
@sawa i thought the way the first way worked was because it first looked for a local variable, didnt find one, and then it look for a getter method. Updated my question to clear up my original misunderstanding. Thank you for pointing that out. If you can help, please help! Or at least remove downvote. Thanks!MicFin

1 Answers

4
votes

Camp 1: Convention over configuration. Also, self.first_name will not work for private accessors.

Camp 2: You know what's what at a glance, whereas you might forget what methods you have without the explicit receiver.

In the end, it's an opinion question, so I'm voting to close. However, food for thought:

bbatsov style guide:

Avoid self where not required. (It is only required when calling a self write accessor.)

GitHub style guide (based on bbatsov style guide):

Avoid explicit use of self as the recipient of internal class or instance messages unless to specify a method shadowed by a variable.