MicFin
MicFin

Reputation: 2501

Is it better practice to use attribute_name or self.attribute_name when accessing within model

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?

Upvotes: 2

Views: 1231

Answers (1)

Amadan
Amadan

Reputation: 198314

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.

Upvotes: 4

Related Questions