4
\$\begingroup\$

I have an action method in my Rails controller which filters an ActiveRecord model depending on the submitted GET parameters.
Rubocop complains that Assignment Branch Condition Size is too high: 20.62/15.

Is there a way to improve the following code?

@measurements = Measurement.all
@measurements = @measurements.where(sensor_id: params[:sensor_id].split(',')) if params[:sensor_id].present?
@measurements = @measurements.last_per_sensor(params[:last_per_sensor]) if params[:last_per_sensor].present?
@measurements = @measurements.last(params[:last]) if params[:last].present?
Vogel612
25.5k7 gold badges59 silver badges141 bronze badges
asked Jun 7, 2016 at 18:43
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Some notes:

  • That's too much code for a controller method, it should be moved to the model.

  • The same name (@measurements) holds up to 4 different values. As a general rule, avoid variable rebinding: different values, different names.

  • More about how the filtering method could be written keeping it DRY: https://stackoverflow.com/a/4480285/188031

For example:

class Measurement < ActiveRecord::Base
 def self.filter(attributes)
 attributes.select { |k, v| v.present? }.reduce(all) do |scope, (key, value)|
 case key.to_sym
 when :sensor_id
 scope.where(key => value)
 when :last, :last_per_sensor 
 scope.send(key, value)
 else
 scope
 end 
 end
 end
end

And in the controller simply:

@measurements = Measurement.filter(params.slice(:sensor_id, :last, :last_per_sensor))
answered Jun 7, 2016 at 22:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.