Daily Refactor #34: Split Methods in the controllers

Back after a short personal break, I’m going to start on another set of refactorings in Redmine to remove some more duplication.

The Refactoring

This time I used split method to separate two behaviors in six similar before_filters.

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
# app/controller/issue_relations_controller.rb
class IssueRelationsController < ApplicationController
  before_filter :find_project, :authorize
 
  private
 
  def find_project
    @issue = Issue.find(params[:issue_id])
    @project = @issue.project
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end

After

1
2
3
4
5
6
7
8
9
10
11
# app/controller/application_controller.rb
class ApplicationController < ActionController::Base
  # Finds and sets @project based on @object.project
  def find_project_from_association
    render_404 unless @object.present?
 
    @project = @object.project
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end
1
2
3
4
5
6
7
8
9
10
11
12
# app/controller/issue_relations_controller.rb
class IssueRelationsController < ApplicationController
  before_filter :find_issue, :find_project_from_association, :authorize
 
  private
 
  def find_issue
    @issue = @object = Issue.find(params[:issue_id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end

Review

This cleans up the #find_issue before_filter so it’s no longer setting project directly. It’s not a very useful refactoring by itself, but it’s set me up to do larger refactoring on all six of the #find_thing filters.

Reference commit