Sha256: 6a762b243f9838919efb1b46eeec83322d7147684912257677875b532f4d6cbb

Contents?: true

Size: 1.2 KB

Versions: 1

Compression:

Stored size: 1.2 KB

Contents

require 'erb'

module Airrecord
  # Airtable expects that arrays in query strings be encoded with indices.
  # Faraday follows Rack conventions and encodes arrays _without_ indices.
  #
  # Airrecord::QueryString is a Faraday-compliant params_encoder that follows
  # the Airtable spec.
  module QueryString
    def self.encode(params)
      params.map { |key, val| Encodings[val].call(key, val) }.join('&')
    end

    def self.decode(query)
      Faraday::NestedParamsEncoder.decode(query)
    end

    def self.escape(*query)
      query.map { |qs| ERB::Util.url_encode(qs) }.join('')
    end

    module Encodings
      using QueryString

      def self.[](value)
        TYPES.fetch(value.class, DEFAULT)
      end

      TYPES = {
        Array => lambda { |prefix, array|
          array.each_with_index.map do |value, index|
            self[value].call("#{prefix}[#{index}]", value)
          end
        },
        Hash => lambda { |prefix, hash|
          hash.map do |key, value|
            self[value].call("#{prefix}[#{key}]", value)
          end
        },
      }.freeze

      DEFAULT = lambda do |key, value|
        "#{QueryString.escape(key)}=#{QueryString.escape(value)}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
airrecord-1.0.0 lib/airrecord/query_string.rb