Class: SleepingKingStudios::Tools::Toolbox::Initializer

Inherits:
Object
  • Object
show all
Defined in:
lib/sleeping_king_studios/tools/toolbox/initializer.rb

Overview

Utility class for initializing a library or project.

An initializer is used to set up the project, including loading configuration, setting initial data or states, and initializing dependencies.

Using an initializer provides several advantages:

  • Potentially-expensive setup code is run on your own schedule, not when the module is first loaded.

  • The setup code will only run once, even if the initializer is called multiple times or from multiple places.

  • The setup code will only run once, even in a multi-threaded environment.

Examples:

Defining An Initializer

module Space
  @initializer = SleepingKingStudios::Tools::Toolbox::Initializer.new do
    # Initializers can safely call other initializers to ensure
    # dependencies are set up.
    Physics.initializer.call

    Space.load_configuration
  end

  def self.initializer = @initializer
end

Calling An Initializer

# In spec/spec_helper.rb

require 'space'

Space.initializer.call

Instance Method Summary collapse

Constructor Details

#initialize { ... } ⇒ Initializer

Returns a new instance of Initializer.

Yields:

  • the block to execute when the initializer is called.

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
# File 'lib/sleeping_king_studios/tools/toolbox/initializer.rb', line 42

def initialize(&block)
  raise ArgumentError, 'no block given' unless block_given?

  @block     = block
  @called    = false
  @semaphore = Thread::Mutex.new
end

Instance Method Details

#callObject

Runs the initialization block exactly once.



51
52
53
54
55
56
57
58
59
# File 'lib/sleeping_king_studios/tools/toolbox/initializer.rb', line 51

def call
  @semaphore.synchronize do
    return if @called

    @block.call

    @called = true
  end
end