patterns

A list of patterns I learned that come around useful. Incomplete and wildy unorganised.

Returning early from controller actions

There are certain situations in which you might want to return early from a controller actions, for example, if you want to make sure a user is allowed to see a certain resource. If a user is not allowed to see said resource, you may want to redirect them somewhere else. redirect_to does not stop the execution of a function though, so this has to be done manually. The most basic way to do that is to use and return, however, validate_access_rights and return does not read very well.

Robert Pankowecki introduces 4 possible ways to return early in his article, the most elegant of which is the foruth: extracted_method; return if performed?.

class Controller
  def show
    verify_something; return if performed?
    @instance_var = Model.find(params[:id])
  end

  private

  def verify_something
    if not_valid?
      redirect_to some_path and return
    end
  end

Further Reading

Memoization

The basic idea here is to cache results of methods to that these methods do not have to be executed over and over again, yielding the same results. Basic memoization can look like this:

class Article < ActiveRecord::Base
  def comments
    @comments ||= article.comments
  end
end

Obviously, this example is very constructed and just used to display the syntax

Further Reading

Last updated