The Refactoring
Using move method I was able to move a chunk of duplicated code from the QueriesController into the Query model.
Before
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # app/controllers/queries_controller.rb def new # ... params[:fields].each do |field| @query.add_filter(field, params[:operators][field], params[:values][field]) end if params[:fields] @query.group_by ||= params[:group_by] # ... end def edit # ... params[:fields].each do |field| @query.add_filter(field, params[:operators][field], params[:values][field]) end if params[:fields] @query.attributes = params[:query] # ... end |
1 2 3 4 | # app/models/query.rb class Query < ActiveRecord::Base # ... end |
After
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # app/controllers/queries_controller.rb class QueriesController < ApplicationController def new # ... @query.add_filters(params[:fields], params[:operators], params[:values]) if params[:fields] @query.group_by ||= params[:group_by] # ... end def edit # ... @query.add_filters(params[:fields], params[:operators], params[:values]) if params[:fields] @query.attributes = params[:query] # ... end end |
1 2 3 4 5 6 7 8 | class Query < ActiveRecord::Base # Add multiple filters using +add_filter+ def add_filters(fields, operators, values) fields.each do |field| add_filter(field, operators[field], values[field]) end end end |
Review
Even though this refactoring is simple, it’s useful for three reasons:
- It reduces the complexity of the Controller
- It removes some duplication in the Controller
- It makes a new method available on the Model that can be reused in other places
Share
Related posts:
