Search code examples
ruby-on-railsrubyrefactoringrake

Refactoring a rake task to be less repetitive


Pretty new to Ruby on Rails here. I'm trying to refactor a rake task. It works fine but I think it could be more concise although I'm not sure where to start. Please offer suggestions on how I might improve this code.

task assign_position_to_items: :environment do
  pos = 0
  MyObject.find(param).checklist_item_sections.order(:id).each do | item |
    item.update(position: pos)
    pos += 1
    item.check_list_items.order(:id).each do | itm |
      itm.update(position: pos)
      pos += 1
      itm.inspection_responses.order(:id).each do | it |
        it.update(position: pos)
        pos += 1
      end
    end
  end
end

Solution

  • You can use Enumerable#each_with_index see api docs to dry this up a bit, and also you can loop over the relation methods to dry it further. Finally you can pass the increment method as a value directly.

    task assign_position_to_items: :environment do
      MyObject.find(param).checklist_item_sections.order(:id).each_with_index do |item, pos|
        item.update(position: pos)
        [:check_list_items, :inspection_responses].each do |method|
          pos += 1
          item.send(method).order(:id) do |children|
            children.upate(position: pos += 1)
          end
        end
      end
    end