Extract class to handle voting style logic

Since we're going to introduce a new voting style which will not be
based on money, we're extracting the logic specific to the current
voting style to a new class.

This way adding new voting styles will be easier.
This commit is contained in:
Javi Martín
2020-07-12 23:59:41 +02:00
parent c22e800329
commit ad094e5063
3 changed files with 36 additions and 16 deletions

View File

@@ -17,26 +17,10 @@ class Budget
investments.sum(:price).to_i
end
def amount_spent(heading)
investments.by_heading(heading.id).sum(:price).to_i
end
def formatted_amount_spent(heading)
budget.formatted_amount(amount_spent(heading))
end
def amount_available(heading)
budget.heading_price(heading) - amount_spent(heading)
end
def formatted_amount_available(heading)
budget.formatted_amount(amount_available(heading))
end
def enough_money?(investment)
investment.price.to_i <= amount_available(investment.heading)
end
def has_lines_in_group?(group)
groups.include?(group)
end
@@ -79,5 +63,17 @@ class Budget
def casted_offline?
budget.poll&.voted_by?(user)
end
def voting_style
@voting_style ||= voting_style_class.new(self)
end
delegate :amount_available, :amount_spent, :enough_money?, :formatted_amount_available,
to: :voting_style
private
def voting_style_class
Budget::VotingStyles::Knapsack
end
end
end

View File

@@ -0,0 +1,7 @@
class Budget::VotingStyles::Base
attr_reader :ballot
def initialize(ballot)
@ballot = ballot
end
end

View File

@@ -0,0 +1,17 @@
class Budget::VotingStyles::Knapsack < Budget::VotingStyles::Base
def enough_money?(investment)
investment.price.to_i <= amount_available(investment.heading)
end
def amount_available(heading)
ballot.budget.heading_price(heading) - amount_spent(heading)
end
def amount_spent(heading)
ballot.investments.by_heading(heading.id).sum(:price).to_i
end
def formatted_amount_available(heading)
ballot.budget.formatted_amount(amount_available(heading))
end
end