Class: Salestation::Web::Extractors::InputCoercer

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

Overview

Handles coercing input values

Examples:

extractor = BodyParamExtractor[:x, :y]
  .coerce(x: ->(value) { "x_#{value}"})
input = {
 'x' => 'a',
 'y' => 'b',
}
# rack_request is Rack::Request with 'rack.request.form_hash' set to input
extractor.call(rack_request).value #=> {x: 'x_a', y: 'b'}

Instance Method Summary collapse

Constructor Details

#initialize(extractor, rules) ⇒ InputCoercer

Returns a new instance of InputCoercer.



73
74
75
76
# File 'lib/salestation/web/extractors.rb', line 73

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

Instance Method Details

#call(rack_request) ⇒ Object



78
79
80
81
82
# File 'lib/salestation/web/extractors.rb', line 78

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

#coerce(input) ⇒ Object



84
85
86
87
88
89
# File 'lib/salestation/web/extractors.rb', line 84

def coerce(input)
  @rules.each do |field, coercer|
    input[field] = coercer.call(input[field]) if input.key?(field)
  end
  Deterministic::Result::Success(input)
end

#merge(other) ⇒ Object



91
92
93
# File 'lib/salestation/web/extractors.rb', line 91

def merge(other)
  CombinedInputExtractor.new([self, other])
end