Class: DiFtw::Singleton

Inherits:
Object
  • Object
show all
Defined in:
lib/diftw/singleton.rb

Overview

Class representing an injected dependency that’s only created once.

Instance Method Summary collapse

Constructor Details

#initialize(y) ⇒ Singleton

A new dependency.

Parameters:

  • y (Proc)

    returns the dependency



11
12
13
14
15
# File 'lib/diftw/singleton.rb', line 11

def initialize(y)
  @y = y
  @val = nil
  @mutex = Mutex.new
end

Instance Method Details

#resolveObject

Return the value for the dependency. If this is the first access, the injected value will be cached and re-used for later injections. Yes, it’s thread-safe.



21
22
23
# File 'lib/diftw/singleton.rb', line 21

def resolve
  @val || @mutex.synchronize { @val ||= @y.call }
end