From ad094e5063cc63503958727980928258eb87891d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Sun, 12 Jul 2020 23:59:41 +0200 Subject: [PATCH] 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. --- app/models/budget/ballot.rb | 28 +++++++++------------ app/models/budget/voting_styles/base.rb | 7 ++++++ app/models/budget/voting_styles/knapsack.rb | 17 +++++++++++++ 3 files changed, 36 insertions(+), 16 deletions(-) create mode 100644 app/models/budget/voting_styles/base.rb create mode 100644 app/models/budget/voting_styles/knapsack.rb diff --git a/app/models/budget/ballot.rb b/app/models/budget/ballot.rb index 70f59fc05..4c4b2370c 100644 --- a/app/models/budget/ballot.rb +++ b/app/models/budget/ballot.rb @@ -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 diff --git a/app/models/budget/voting_styles/base.rb b/app/models/budget/voting_styles/base.rb new file mode 100644 index 000000000..48de3a032 --- /dev/null +++ b/app/models/budget/voting_styles/base.rb @@ -0,0 +1,7 @@ +class Budget::VotingStyles::Base + attr_reader :ballot + + def initialize(ballot) + @ballot = ballot + end +end diff --git a/app/models/budget/voting_styles/knapsack.rb b/app/models/budget/voting_styles/knapsack.rb new file mode 100644 index 000000000..6c056115e --- /dev/null +++ b/app/models/budget/voting_styles/knapsack.rb @@ -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