Defaultblog

Ruby on Rails QuickTip: Wrapping simple chunks of code in a method to give it meaning

ruby ruby on rails software

Let's say you have a model of a User. Let's say that if the user's birth year is 1990 or before, then you can't edit that user's first name. So you might have something like this:

# User Class
class User < ApplicationRecord
end

and you might have something like this

# User controller
class UsersController < ApplicationController
  def edit
    if user.birth_year <= 1990
       # don't allow editing of first name
    end
end

However, I would argue, that even though it's a really simply check, that you should put this in its own method:

# User Class
class User < ApplicationRecord
  def first_name_locked?
    birth_year <= 1990
  end
end
# User controller
class UsersController < ApplicationController
  def edit
    if user.first_name_locked?
       # don't allow editing of first name
    end
end

Very simple implementation and achieves the same result, but here are some advantages

  • The condition is now given meaning so that developers who are using it can understand its intent
  • Any developer reading any code that uses that method will understand more easily what's happening
  • If the business logic changes for locking the first name, you'll have to edit only one piece of code

So even the simplest pieces of code can benefit from wrapping them in a method.

Caseyli
Casey Li
CEO & Founder, BiteSite