Leo lou
Leo lou

Reputation: 19

How to refactor and reduce complexity

I have the following code:

@model = "ford"
@attribute = "name"

def grouped
   grouped = {}

   @array.each do |r|
     field = r.car.send(@model)

     if field.is_a? ActiveRecord::Associations::CollectionProxy
        field.each do |obj|
           key = obj.send(@attribute)
           grouped[key] = [] unless grouped.has_key?(key)
           grouped[key].push(r)
       end
     else
       key = field.send(@attribute)
       grouped[key] = [] unless grouped.has_key?(key)
       grouped[key].push(r)
     end
   end

  grouped
end

The result is:

{ford: [a, b, c]}

The codeclimate says that it has cognitive complexity.

How can I refactor this method to something cleaner?

Upvotes: 1

Views: 812

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

def grouped
   @array.each_with_object(Hash.new { |h, k| h[k] = [] }) do |r, grouped|
     case field = r.car.send(@model)
     when ActiveRecord::Associations::CollectionProxy
        field.each do |obj|
          grouped[obj.send(@attribute)] << r
        end
     else
       grouped[field.send(@attribute)] << r
     end
   end
end

Upvotes: 2

Related Questions