Class: Decidim::Gamification::BadgeRegistry

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

Overview

This class represents a repository of badges. New badges can be registered thanks to its DSL and will be validated prior to being inserted.

Instance Method Summary collapse

Constructor Details

#initializeBadgeRegistry

Public: Initializes the badge registry.



11
12
13
# File 'lib/decidim/gamification/badge_registry.rb', line 11

def initialize
  @badges = {}
end

Instance Method Details

#allObject

Public: Returns all the registered badges.

Returns Array<Badge>.



18
19
20
# File 'lib/decidim/gamification/badge_registry.rb', line 18

def all
  @badges.values
end

#find(name) ⇒ Object

Public: Finds a badge given its name.

name - The name of the badge to find.

Returns a Badge if found or nil otherwise.



27
28
29
# File 'lib/decidim/gamification/badge_registry.rb', line 27

def find(name)
  @badges[name.to_s]
end

#register(name, &block) ⇒ Object

Public: Registers a new badge.

name - The name of the badge to register. &block - A block that gets the new badge as argument.

Example:

register(:fake){ |badge| badge.levels = [1, 3, 10] }

Returns a Badge when registered successfully, raises an exception otherwise.



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/decidim/gamification/badge_registry.rb', line 41

def register(name, &block)
  name = name.to_s

  badge = Badge.new(name: name).tap do |object|
    object.instance_eval(&block)
  end

  badge.validate!

  @badges[name] = badge
end

#unregister(name) ⇒ Object

Public: Unregisters a previously registered badge.

name - The name of the badge to unregister.

Returns the deleted Badge if found, nil otherwise.



58
59
60
# File 'lib/decidim/gamification/badge_registry.rb', line 58

def unregister(name)
  @badges.delete(name.to_s)
end