Sha256: 02df2b2e7642eba5716abfc8f9bdeac19873d7194141b589c671cbf75ac25572

Contents?: true

Size: 1.17 KB

Versions: 6

Compression:

Stored size: 1.17 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
      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

6 entries across 6 versions & 1 rubygems

Version Path
airrecord-1.0.6 lib/airrecord/query_string.rb
airrecord-1.0.5 lib/airrecord/query_string.rb
airrecord-1.0.4 lib/airrecord/query_string.rb
airrecord-1.0.3 lib/airrecord/query_string.rb
airrecord-1.0.2 lib/airrecord/query_string.rb
airrecord-1.0.1 lib/airrecord/query_string.rb