Created
February 23, 2015 10:36
-
-
Save srpouyet/9d40e3a6a4b08f89f289 to your computer and use it in GitHub Desktop.
Faraday PreserveKeysEncoder: Only decodes url parameter values and leaves keys intact.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## PreserveKeysEncoder doesn't encode parameter keys (which is standard Faraday behaviour). | |
## Usage: | |
## Faraday.new(url, request: { params_encoder: PreserveKeysEncoder.new }) | |
## Modes: | |
## :nested { '$product_id' =>' [10,20,30] } becomes $product_id[1]=10&$product_id[1]=20&$product_id[1]=30 | |
## :flat and $product_id=10&$product_id=20&$product_id=30 in :flat mode | |
class Faraday::PreserveKeysEncoder | |
MODES = [:nested, :flat] | |
delegate :decode, :escape, to: :super_encoder, allow_nil: true | |
attr_reader :mode | |
MODES.each{ |mode_name| define_method("#{mode_name}?"){ mode == mode_name } } | |
def initialize(mode: :nested) | |
@mode = mode.intern | |
end | |
def encode(params) | |
return nil if params.nil? | |
params.to_a.map{ |param| param_to_string(param) }.compact.join('&') | |
end | |
private | |
def super_encoder | |
case mode | |
when :flat then Faraday::FlatParamsEncoder | |
when :nested then Faraday::NestedParamsEncoder | |
end | |
end | |
def param_to_string(param) | |
key, value = param # Input should be [key, param]. | |
case value | |
when nil, '' then nil | |
when Array | |
value.each_with_index.map do |e, i| | |
sub_key = nested? ? "#{key}#{[i+1]}" : key | |
param_to_string([sub_key, e]) | |
end.join('&') | |
else "#{key}=#{escape(value)}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment