Class: Openra::Struct::PreProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/openra/struct/pre_processor.rb

Constant Summary collapse

AlreadyFinalizedError =
Class.new(StandardError)
NotFinalizedError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**config) ⇒ PreProcessor

Returns a new instance of PreProcessor.



11
12
13
# File 'lib/openra/struct/pre_processor.rb', line 11

def initialize(**config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



9
10
11
# File 'lib/openra/struct/pre_processor.rb', line 9

def config
  @config
end

Instance Method Details

#call(input) ⇒ Object



15
16
17
# File 'lib/openra/struct/pre_processor.rb', line 15

def call(input)
  transformer.call(input)
end

#finalize!Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/openra/struct/pre_processor.rb', line 24

def finalize!
  config = self.config

  transformer_klass = Class.new(Dry::Transformer::Pipe[Functions])
  transformer_klass.instance_eval do
    define! do
      unwrap(config[:root]) if config[:root]

      if (schema = config[:schema])
        schema.keys.each do |key|
          if (sequence = key.type.meta[:sequence])
            sequence(sequence, sequence)
            rename_keys(sequence => key.name)
          end
        end

        mapping = schema.keys.each_with_object({}) do |key, mapping|
          mapping[key.type.meta[:from]] = key.name if key.type.meta[:from]
        end

        rename_keys(mapping)
      end
    end
  end

  @transformer = transformer_klass.new
  @finalized = true
end

#with(**new_config) ⇒ Object



19
20
21
22
# File 'lib/openra/struct/pre_processor.rb', line 19

def with(**new_config)
  raise AlreadyFinalizedError, 'transformer already finalized' if finalized?
  self.class.new(**config.merge(new_config))
end