Class: Salestation::Web::Extractors::InputRenamer

Inherits:
Object
  • Object
show all
Defined in:
lib/salestation/web/extractors.rb

Overview

Handles renaming input keys

When renaming we want to ensure that the new key provided for the rename does not already exist in the input. When it does and it has a not nil value, then rename will not happen, unless ‘override: true` is also applied. When the new key exists with nil value, rename will happen. By default override is set to false: when input already has value set for the new key, the old key will be discarded instead of overwriting the value. For deprecating (renaming for deprecation purposes), one should extract both new and old key from the input before calling the rename function, to get expected result, as only then the values can be compared in rename.

Examples:

original_input = {
  x: 'a',
  y: 'b'
}

extractor = BodyParamExtractor[:x, :y]
  .rename(x: :z)
input = {
  z: 'a',
  y: 'b'
}

extractor = BodyParamExtractor[:x, :y]
  .rename(x: :y)
input = {
  y: 'b'
}
extractor = BodyParamExtractor[:x, :y]
  .rename(x: {new_key: :y, override: true})
input = {
  y: 'a'
}

Instance Method Summary collapse

Constructor Details

#initialize(extractor, rules) ⇒ InputRenamer

Returns a new instance of InputRenamer.



132
133
134
135
# File 'lib/salestation/web/extractors.rb', line 132

def initialize(extractor, rules)
  @extractor = extractor
  @rules = map_rules(rules)
end

Instance Method Details

#call(rack_request) ⇒ Object



137
138
139
140
141
# File 'lib/salestation/web/extractors.rb', line 137

def call(rack_request)
  @extractor
    .call(rack_request)
    .map(&method(:rename))
end

#rename(input) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/salestation/web/extractors.rb', line 143

def rename(input)
  @rules.each do |old_key, rule|
    new_key = rule[:new_key]
    override = rule[:override]

    if input[new_key].nil? || override
      input[new_key] = input[old_key]
    end

    input.delete(old_key)
  end
  Deterministic::Result::Success(input)
end