Class: Decidim::Gamification::BadgeScorer

Inherits:
Object
  • Object
show all
Defined in:
lib/decidim/gamification/badge_scorer.rb

Overview

This class is responsible of updating scores given a model and a badge. Will also trigger any side-effects such as notifications.

Defined Under Namespace

Classes: InvalidAmountException, NegativeScoreException

Instance Method Summary collapse

Constructor Details

#initialize(model, badge) ⇒ BadgeScorer

Public: Initializes the class.

model - The model for which to update scores. badge - The ‘Badge` to update.



13
14
15
16
17
18
# File 'lib/decidim/gamification/badge_scorer.rb', line 13

def initialize(model, badge)
  raise "Invalid badge for this UserBase type" unless badge.valid_for?(model)

  @model = model
  @badge = badge
end

Instance Method Details

#decrement(amount = 1) ⇒ Object

Public: Decrements the score for the model and badge.

amount - Amount to decrement. Defaults to 1.

Returns a ‘BadgeScore`.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/decidim/gamification/badge_scorer.rb', line 41

def decrement(amount = 1)
  raise InvalidAmountException unless amount.positive?

  with_level_tracking do
    badge_score = BadgeScore.find_by(
      user: @model,
      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 model and badge.

amount - Amount to increment. Defaults to 1.

Returns a ‘BadgeScore`.



25
26
27
28
29
30
31
32
33
34
# File 'lib/decidim/gamification/badge_scorer.rb', line 25

def increment(amount = 1)
  raise InvalidAmountException unless amount.positive?

  with_level_tracking do
    BadgeScore.find_or_create_by(
      user: @model,
      badge_name: @badge.name
    ).increment(:value, amount).save!
  end
end

#set(score) ⇒ Object

Public: Sets the score for the model and badge.

score - Score to set.

Returns a ‘BadgeScore`.



63
64
65
66
67
68
69
70
71
72
# File 'lib/decidim/gamification/badge_scorer.rb', line 63

def set(score)
  raise NegativeScoreException if score.negative?

  with_level_tracking do
    BadgeScore.find_or_create_by(
      user_id: @model.id,
      badge_name: @badge.name
    ).update!(value: score)
  end
end