Class: Decidim::Gamification::BadgeScorer
- Inherits:
-
Object
- Object
- Decidim::Gamification::BadgeScorer
- Defined in:
- lib/decidim/gamification/badge_scorer.rb
Overview
This class is responsible of updating scores given a user and a badge. Will also trigger any side-effects such as notifications.
Defined Under Namespace
Classes: InvalidAmountException, NegativeScoreException
Instance Method Summary collapse
-
#decrement(amount = 1) ⇒ Object
Public: Decrements the score for the user and badge.
-
#increment(amount = 1) ⇒ Object
Public: Increments the score for the user and badge.
-
#initialize(user, badge) ⇒ BadgeScorer
constructor
Public: Initializes the class.
-
#set(score) ⇒ Object
Public: Sets the score for the user and badge.
Constructor Details
#initialize(user, badge) ⇒ BadgeScorer
Public: Initializes the class.
user - The user for which to update scores. badge - The ‘Badge` to update.
13 14 15 16 |
# File 'lib/decidim/gamification/badge_scorer.rb', line 13 def initialize(user, badge) @user = user @badge = badge end |
Instance Method Details
#decrement(amount = 1) ⇒ Object
Public: Decrements the score for the user and badge.
amount - Amount to decrement. Defaults to 1.
Returns a ‘BadgeScore`.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/decidim/gamification/badge_scorer.rb', line 39 def decrement(amount = 1) raise InvalidAmountException unless amount.positive? with_level_tracking do badge_score = BadgeScore.find_by( user: @user, badge_name: @badge.name ) next if badge_score.blank? badge_score.decrement(:value, amount) badge_score.value = 0 if badge_score.value.negative? badge_score.save! end end |
#increment(amount = 1) ⇒ Object
Public: Increments the score for the user and badge.
amount - Amount to increment. Defaults to 1.
Returns a ‘BadgeScore`.
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/decidim/gamification/badge_scorer.rb', line 23 def increment(amount = 1) raise InvalidAmountException unless amount.positive? with_level_tracking do BadgeScore.find_or_create_by( user: @user, badge_name: @badge.name ).increment(:value, amount).save! end end |
#set(score) ⇒ Object
Public: Sets the score for the user and badge.
score - Score to set.
Returns a ‘BadgeScore`.
61 62 63 64 65 66 67 68 69 70 |
# File 'lib/decidim/gamification/badge_scorer.rb', line 61 def set(score) raise NegativeScoreException if score.negative? with_level_tracking do BadgeScore.find_or_create_by( user_id: @user.id, badge_name: @badge.name ).update!(value: score) end end |