Ruby on Rails controllers are an easy place to get code creep (a lot of code in a place where it shouldn’t be or unneeded code). The following is one simple way we have refactored some of our very large controllers for easy readability.

The way most books show you.

1
2
3
4
5
6
7
8
9
class SearchController < ApplicationController
 
  before_filter :initialize_search, :only => [:search_results]
  before_filter :verify_locations, :only => [:search_results]
  before_filter :ambiguous_locations, :only => [:search_results]
  before_filter :verify_time, :only => [:search_results]
  before_filter :grace_period, :only => [:search_results]
 
#...
122
123
124
125
126
127
128
129
130
131
132
 
#...
 
  def search_results
    @search_results = run_search
    if @search_results.empty?
      @errors << 'No results, try a new search'.t
      return render_results
    end 
    @search_results
  end

The way we have refactored is this.

122
123
124
125
126
127
128
129
130
131
132
133
134
135
 
  before_filter :initialize_search, :only => [:search_results]
  before_filter :verify_locations, :only => [:search_results]
  before_filter :ambiguous_locations, :only => [:search_results]
  before_filter :verify_time, :only => [:search_results]
  before_filter :grace_period, :only => [:search_results]
  def search_results
    @search_results = run_search
    if @search_results.empty?
      @errors << 'No results, try a new search'.t
      return render_results
    end 
    @search_results
  end

The difference here is subtle. Having the before_filters directly above the controller action makes for easy reading if your controllers are complex. Typically I will see controllers hooks at the top of the file stretching 50-100 lines. This writing style improves the speed of knowing what hooks pertain to each action while reading the action. No more flipping back and forth around the file.

Leave a Reply

Your email address will not be published. Required fields are marked *