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

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

Overview

Handles coercing input values

Examples:

extractor = Salestation::Web::Extractors::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(input)).value
#=> {x: 'x_a', y: 'b'}

Instance Method Summary collapse

Constructor Details

#initialize(extractor, rules) ⇒ InputCoercer

Returns a new instance of InputCoercer.



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

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

Instance Method Details

#call(rack_request) ⇒ Object



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

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

#coerce(input) ⇒ Object



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

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



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

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