Class: Trailblazer::Context::ContainerChain

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

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)



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

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

Class Method Details

.find(containers, name) ⇒ Object



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

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.



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

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

#key?(name) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#to_hashObject



33
34
35
36
# File 'lib/trailblazer/container_chain.rb', line 33

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