back

When to use self in Rails models

The problem

Self is overused.

When I started with Rails, half the words in my models were self. This wasn’t necessary. Now, when I edit code by other people, I find myself constantly deleting “self” from their code.

For example:

1
2
3
4
5
class User < ActiveRecord::Base
  def full_name
    "#{self.first_name} #{self.last_name}"
  end
end

Is more readable as:

1
2
3
4
5
class User < ActiveRecord::Base
  def full_name
    "#{first_name} #{last_name}"
  end
end

This becomes even worse when dealing with collections, as a seemingly simple map can quickly stretch to two lines if you double the characters with overzealous self usage.

However, as most of you probably know, you do have to use self for assignment.

Assignment

For assignment, self is necessary. This won’t work:

1
2
3
4
5
class User < ActiveRecord::Base
  def set_first_name_to_wilfred
     first_name = 'wilfred'
  end
end

This, obv will.

1
2
3
4
5
class User < ActiveRecord::Base
  def set_first_name_to_wilfred
     self.first_name = 'wilfred'
  end
end

If Ruby/Rails always assumed that non-explicit assignment were to attributes, then it would quickly become confusing what were local variables and what were an attribute setters.

In practice, then, self must always be explicit for setting attributes, but not for retrieving them.

Guidelines

To take advantage of this, I just do the following:

a. Never use local variables that are the same name as attributes, as that would lead others to, when skimming code, mistake a local variable assignment for an attribute assignment.

b. Never use self for retrieving values, since it’s unnecessary and adds bulk.

Simple.

May 21, 2009