Daily Refactor #71: Extract Method in KanbansController to before_filter

The code in the Redmine Merge plugin looks pretty good so I’m going back to my Redmine Kanban plugin.

Today’s refactoring was guided by the Rails Best Practices gem. This gem uses static code analysis to search for common smells in Rails applications. Running it on Redmine Kanban showed several smells I can tackle:

./app/controllers/kanbans_controller.rb:8,13 - use before_filter for show,update
./app/views/settings/_kanban_settings.html.erb:11 - move code into controller
./app/views/settings/_kanban_settings.html.erb:30 - move code into controller
./app/views/settings/_kanban_settings.html.erb:69 - move code into controller
./app/views/settings/_kanban_settings.html.erb:85 - move code into controller
./app/models/kanban_pane/incoming_pane.rb:8 - keep finders on their own model
./app/views/settings/_kanban_settings.html.erb:6 - move code into model (@settings)
./app/views/settings/_kanban_settings.html.erb:7 - move code into model (@settings)
./app/views/settings/_kanban_settings.html.erb:63 - move code into model (@settings)
./app/views/settings/_kanban_settings.html.erb:64 - move code into model (@settings)
./app/views/settings/_kanban_settings.html.erb:79 - move code into model (@settings)
./app/views/settings/_kanban_settings.html.erb:80 - move code into model (@settings)

The Refactoring

I’m starting with an extract method in KanbansController.

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class KanbansController < ApplicationController
 
  def show
    @settings = Setting.plugin_redmine_kanban
    @kanban = Kanban.new
  end
 
  def update
    @settings = Setting.plugin_redmine_kanban
    @from = params[:from]
    @to = params[:to]
    user_and_user_id
    # ...
  end
end

After

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class KanbansController < ApplicationController
  before_filter :setup_settings
 
  def show
    @kanban = Kanban.new
  end
 
  def update
    @from = params[:from]
    @to = params[:to]
    user_and_user_id
    # ...
  end
 
  def setup_settings
    @settings = Setting.plugin_redmine_kanban
  end
end

Review

These refactorings are one of my favorites. They are simple and help to highlight the differences between different methods. Just like waves on a coastline, they can really change the feel of code over time.

Reference commit