Using self in Ruby
One of the things that had me confused early on when programming in Ruby was when to use “self” for a method and when not to.
The easiest way to summarise, I think, is to say that
self.methodshould be used when referring to a method that operates on the class itself.
methodshould be used when referring to a method that operates on an instance of the class.
The most common place this is seen in Rails application is in authentication systems. The method for logging a user into an application is usually written as:
1 2 3 4 5 6 7 |
Class User < ActiveRecord::Base def self.authenticate(user, password) ... end end |
This is then called in the controller as:
1 2 3 4 5 6 7 |
Class SessionsController < ActionController::Base def new @user = User.authenticate(params[:session]) end end |
In contrast, methods can then be called on the @user object once the user has logged in. For example, to check if the user is an administrator, the following method could be used in our User class:
1 2 3 |
def is_admin? ... end |
This could then be called within the view, perhaps to display certain restricted information:
<%= if @user.is_admin? %> |
As a complete aside, I love how the above code demonstrates the readability of Ruby. There is no doubt as to what that statement means.