Class: Scorecard::Subscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/scorecard/subscriber.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attach_to(suffix) ⇒ Object



2
3
4
5
6
7
8
9
# File 'lib/scorecard/subscriber.rb', line 2

def self.attach_to(suffix)
  subscriber = new
  subscriber.public_methods(false).each do |event|
    next if event.to_s == 'call'

    ActiveSupport::Notifications.subscribe "#{event}.#{suffix}", subscriber
  end
end

Instance Method Details

#badge(event) ⇒ Object



16
17
18
# File 'lib/scorecard/subscriber.rb', line 16

def badge(event)
  Scorecard::Badger.update event.payload[:user]
end

#call(message, *args) ⇒ Object



11
12
13
14
# File 'lib/scorecard/subscriber.rb', line 11

def call(message, *args)
  method = message.split('.').first
  send method, ActiveSupport::Notifications::Event.new(message, *args)
end

#points(event) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/scorecard/subscriber.rb', line 20

def points(event)
  rule = Scorecard.rules.find event.payload[:context]
  return if rule.nil?

  event.payload[:amount]     ||= rule.amount
  event.payload[:identifier] ||= event.payload[:gameable].id
  event.payload[:user]       ||= event.payload[:gameable].user

  return unless rule && rule.allowed?(event.payload)

  point = Scorecard::Point.create(
    event.payload.slice(:context, :amount, :identifier, :user, :gameable)
  )
  ActiveSupport::Notifications.instrument(
    'scorecard', user: event.payload[:user]
  ) if point.persisted?
end

#progress(event) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/scorecard/subscriber.rb', line 38

def progress(event)
  Scorecard.progressions.each do |progression|
    if progression.check.call event.payload[:user]
      progress = Scorecard::Progress.create(
        user: event.payload[:user], identifier: progression.identifier
      )

      ActiveSupport::Notifications.instrument(
        'progress.scorecard', user: event.payload[:user]
      ) if progress.persisted?
    else
      progresses = Scorecard::Progress.for_user(event.payload[:user]).
        for_identifier(progression.identifier)
      progresses.each &:destroy

      ActiveSupport::Notifications.instrument(
        'progress.scorecard', user: event.payload[:user]
      ) if progresses.any?
    end
  end
end