class Scorecard::Badger

Attributes

badge[R]
user[R]

Public Class Methods

new(user, badge) click to toggle source
# File lib/scorecard/badger.rb, line 8
def initialize(user, badge)
  @user, @badge = user, badge
end
update(user) click to toggle source
# File lib/scorecard/badger.rb, line 2
def self.update(user)
  Scorecard.badges.each do |badge|
    new(user, badge).update
  end
end

Public Instance Methods

update() click to toggle source
# File lib/scorecard/badger.rb, line 12
def update
  if badge.check.call user
    return unless existing.empty? || badge.repeatable?

    remove_old
    add_new
  else
    remove_all
  end
end

Private Instance Methods

add_new() click to toggle source
# File lib/scorecard/badger.rb, line 27
def add_new
  new_gameables.each do |gameable|
    user_badge = Scorecard::UserBadge.create(
      badge:      badge.identifier,
      gameable:   gameable,
      user:       user,
      identifier: gameable.id
    )

    ActiveSupport::Notifications.instrument(
      'badge.scorecard', user: user,
      badge: Scorecard::AppliedBadge.new(badge.identifier, user),
      gameable: gameable
    ) if user_badge.persisted?
  end
end
existing() click to toggle source
# File lib/scorecard/badger.rb, line 44
def existing
  @existing ||= Scorecard::UserBadge.for badge.identifier, user
end
gameables() click to toggle source
# File lib/scorecard/badger.rb, line 48
def gameables
  @gameables ||= badge.repeatable? ? badge.gameables.call(user) : [user]
end
new_gameables() click to toggle source
# File lib/scorecard/badger.rb, line 52
def new_gameables
  gameables.reject { |gameable|
    existing.any? { |existing| existing.gameable == gameable }
  }
end
old_user_badges() click to toggle source
# File lib/scorecard/badger.rb, line 58
def old_user_badges
  existing.reject { |user_badge|
    gameables.any? { |gameable| user_badge.gameable == gameable }
  }
end
remove(user_badge) click to toggle source
# File lib/scorecard/badger.rb, line 64
def remove(user_badge)
  user_badge.destroy

  ActiveSupport::Notifications.instrument 'unbadge.scorecard',
    user: user, badge: badge.identifier, gameable: user_badge.gameable
end
remove_all() click to toggle source
# File lib/scorecard/badger.rb, line 71
def remove_all
  existing.each { |user_badge| remove user_badge }
end
remove_old() click to toggle source
# File lib/scorecard/badger.rb, line 75
def remove_old
  old_user_badges.each { |user_badge| remove user_badge }
end