Daily Refactor #56: Replace Accumulator with Inject

The Refactoring

Today’s refactoring is a simple one that makes use of Ruby’s #inject. #inject is a great method for building accumulators but I don’t see it that often in Rails code that much (including my own).

Before

1
2
3
4
5
6
7
8
9
10
11
12
# app/models/kanban_pane/active_pane.rb
class KanbanPane::ActivePane < KanbanPane
  def get_issues(options={})
    users = options.delete(:users)
 
    issues = {}
    users.each do |user|
      issues[user] = KanbanIssue.find_active(user.id)
    end unless users.blank?
    issues
  end
end

After

1
2
3
4
5
6
7
8
9
10
11
# app/models/kanban_pane/active_pane.rb
class KanbanPane::ActivePane < KanbanPane
  def get_issues(options={})
    users = options.delete(:users)
 
    users.inject({}) do |result, user|
      result[user] = KanbanIssue.find_active(user.id)
      result
    end
  end
end

Review

Jay Fields has posted several other examples of using #inject. I still go back to that blog post every few months and learn something new.

Reference commit