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

Share

  • Facebook
  • Twitter
  • HackerNews
  • Reddit
  • Tumblr
  • Delicious
  • Email
  • RSS

Related posts:

  1. Redmine Refactor #125: Split UsersController#edit into #edit and #update
  2. Redmine Refactor #123: Split #add method in UsersController to #add and #create
  3. Redmine Refactor #118: Split Edit Method in NewsController
  4. Redmine Refactor #117: Split New Method in NewsController
  5. Redmine Refactor #115: Split Method in VersionsController

About Eric Davis

I founded Little Stream Software where I provide Redmine and ChiliProject services to help projects teams. I also created an ebook, Redmine Tips, were I show you how to become more productive using Redmine. I am also the author of Refactoring Redmine, where I go about refactoring Rails using Redmine as an example.

, , ,

Chirk HR     Reuse your existing job applicants »
WP Socializer Aakash Web