Files
nairobi/app/models/budget/result.rb
Bertocq efacd0def3 Make calculate_winners explicitly delayed
Why:

* As seen on preproduction and production environments on Madrid's fork. Budget::Result#calculate_winners is very costly when done to all headings for a given budget (as requested on Admin::BudgetsController#calculate_winners) but its not when done individually for only a heading (as requested on Budget::Investment#recalculate_heading_winners)

How:

* Removing `handle_asynchronously :calculate_winners` from bellow Budget::Result#calculate_winners definition, to avoid making any call delayed. And explicitly calling `.delay` only when needed (on Admin::BudgetsController#calculate_winners)
2017-07-10 15:12:14 +02:00

54 lines
993 B
Ruby

class Budget
class Result
attr_accessor :budget, :heading, :money_spent, :current_investment
def initialize(budget, heading)
@budget = budget
@heading = heading
end
def calculate_winners
reset_winners
investments.compatible.each do |investment|
@current_investment = investment
set_winner if inside_budget?
end
end
def investments
heading.investments.selected.sort_by_ballots
end
def inside_budget?
available_budget >= @current_investment.price
end
def available_budget
total_budget - money_spent
end
def total_budget
heading.price
end
def money_spent
@money_spent ||= 0
end
def reset_winners
investments.update_all(winner: false)
end
def set_winner
@money_spent += @current_investment.price
@current_investment.update(winner: true)
end
def winners
investments.where(winner: true)
end
end
end