Class: Trailblazer::Context::ContainerChain

Inherits:
Object
  • Object
show all
Defined in:
lib/trailblazer/container_chain.rb

Overview

used to be called Resolver.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(containers, to_hash: nil) ⇒ ContainerChain

Note:

ContainerChain is an immutable data structure, it does not support writing.

Keeps a list of containers. When looking up a key/value, containers are traversed in the order they were added until key is found.

Required Container interface: `#key?`, `#[]`.

Parameters:

  • containers

    Array of <Container> objects (splatted)


11
12
13
14
# File 'lib/trailblazer/container_chain.rb', line 11

def initialize(containers, to_hash: nil)
  @containers = containers
  @to_hash    = to_hash
end

Class Method Details

.find(containers, name) ⇒ Object


26
27
28
# File 'lib/trailblazer/container_chain.rb', line 26

def self.find(containers, name)
  containers.find { |container| container.key?(name) && (return container[name]) }
end

Instance Method Details

#[](name) ⇒ Object

Parameters:

  • name

    Symbol or String to lookup a value stored in one of the containers.


17
18
19
# File 'lib/trailblazer/container_chain.rb', line 17

def [](name)
  self.class.find(@containers, name)
end

#key?(name) ⇒ Boolean

Returns:

  • (Boolean)

22
23
24
# File 'lib/trailblazer/container_chain.rb', line 22

def key?(name)
  @containers.find { |container| container.key?(name) }
end

#keysObject


30
31
32
# File 'lib/trailblazer/container_chain.rb', line 30

def keys
  @containers.collect(&:keys).flatten
end

#to_hashObject


35
36
37
38
39
# File 'lib/trailblazer/container_chain.rb', line 35

def to_hash
  # FIXME: introduce pattern matching so we can have different "transformers" for each container type.
  return @to_hash.(@containers) if @to_hash
  @containers.each_with_object({}) { |container, hash| hash.merge!(container.to_hash) }
end