The most common smell in Rails applications is the Long Method.
Long methods are exactly what they sound like: methods that are too
long. They’re easy to spot.
- If you can’t tell exactly what a method does at a glance, it’s too
- Methods with more than one level of nesting are usually too
- Methods with more than one level of abstraction may be too
- Methods with a flog score of 10 or higher may be too long.
You can watch out for long methods as you write them, but finding
existing methods is easiest with tools like flog:
% flog app lib
72.9: flog total
5.6: flog/method average
15.7: QuestionsController#create app/controllers/questions_controller.rb:9
11.7: QuestionsController#new app/controllers/questions_controller.rb:2
8.1: SurveysController#create app/controllers/surveys_controller.rb:6
Methods with higher scores are more complicated. Anything with a
score higher than 10 is worth looking at, but flog only helps you find
potential trouble spots; use your own judgment when refactoring.
For an example of a long method, let’s take a look at the highest
scored method from flog,
@survey = Survey.find(params[:survey_id])
@submittable_type = params[:submittable_type_id]
:submittable_type, :title, :options_attributes, :minimum, :maximum)
permit(@question = @survey.questions.new(question_params)
@question.submittable_type = @submittable_type
After extracting methods, check for feature envy in the new
methods to see if you should employ move method to provide the
method with a better home.
The canonical reference for writing fantastic Rails applications from authors who have created hundreds.
Work with us to make a new Rails app, or to maintain, improve, or scale your existing app.