Module: Phaedra::Initializers

Defined in:
lib/phaedra/initializers_module.rb

Defined Under Namespace

Classes: Registration

Constant Summary collapse

DEFAULT_PRIORITY =
20
PRIORITY_MAP =
{
  low: 10,
  normal: 20,
  high: 30,
}.freeze
NotAvailable =
Class.new(RuntimeError)
Uncallable =
Class.new(RuntimeError)

Class Method Summary collapse

Class Method Details

.prioritized_initializersObject



61
62
63
64
65
66
67
# File 'lib/phaedra/initializers_module.rb', line 61

def self.prioritized_initializers
  # sort initializers according to priority and load order
  grouped_initializers = @registry.group_by(&:priority)
  grouped_initializers.keys.sort.reverse.map do |priority|
    grouped_initializers[priority]
  end.flatten
end

.priority_value(priority) ⇒ Object

Ensure the priority is a Fixnum



29
30
31
32
33
# File 'lib/phaedra/initializers_module.rb', line 29

def self.priority_value(priority)
  return priority if priority.is_a?(Integer)

  PRIORITY_MAP[priority] || DEFAULT_PRIORITY
end

.register(origin, priority: DEFAULT_PRIORITY, &block) ⇒ Object

Raises:



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/phaedra/initializers_module.rb', line 35

def self.register(origin, priority: DEFAULT_PRIORITY, &block)
  raise Uncallable, "Initializers must respond to :call" unless block.respond_to? :call

  @registry << Registration.new(
    origin: origin,
    priority: priority_value(priority),
    block: block
  )

  block
end

.remove(origin) ⇒ Object



47
48
49
# File 'lib/phaedra/initializers_module.rb', line 47

def self.remove(origin)
  @registry.delete_if { |item| item.origin == origin }
end

.run(force: false) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/phaedra/initializers_module.rb', line 51

def self.run(force: false)
  if !@initializers_ran || force
    prioritized_initializers.each do |initializer|
      initializer.block.call
    end
  end

  @initializers_ran = true
end