Sha256: 5a88e3142ff305d44bfc6a9256c5c205de8548ab52adce795ef6ed1675db8ed2

Contents?: true

Size: 1.54 KB

Versions: 8

Compression:

Stored size: 1.54 KB

Contents

class Apisync
  module Http
    class QueryString
      def initialize(filters:)
        @filters = filters
      end

      def to_s
        result = ""
        result << format_filters if @filters
        result
      end

      private

      # Takes a list of `[key]=value` strings and maps them adding `"filter"`
      # as prefix.
      #
      # Results in `filter[key]=value&filter[key2]=value2`.
      def format_filters
        recursive_brackets(@filters)
          .flatten
          .map { |filter| "filter#{filter}" }
          .join("&")
      end

      # Takes a hash such as
      #
      #   {
      #     field_one: 'value1',
      #     metadata: {
      #       field_two: "value2",
      #       field_three: "value3"
      #     }
      #   }
      #
      # and returns
      #
      #   [
      #     "[field-one]=value1",
      #     "[metadata][field-two]=value2",
      #     "[metadata][field-three]=value3"
      #   ]
      #
      # This can be used for creating filter querystrings.
      def recursive_brackets(hash, prefix = "")
        result = []
        hash.each do |key, value|
          key = hyphenize(key.to_s)
          if value.is_a?(Hash)
            prefix = "#{prefix}[#{key}]"
            top_nodes = recursive_brackets(value, prefix)
            result << top_nodes
          else
            result << "#{prefix}[#{key}]=#{value}"
          end
        end

        result
      end

      # Converts application_id in application-id.
      def hyphenize(string)
        string.gsub(/_/, "-")
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
apisync-0.2.3 lib/apisync/http/query_string.rb
apisync-0.2.2 lib/apisync/http/query_string.rb
apisync-0.2.1 lib/apisync/http/query_string.rb
apisync-0.2.0 lib/apisync/http/query_string.rb
apisync-0.1.6 lib/apisync/http/query_string.rb
apisync-0.1.5 lib/apisync/http/query_string.rb
apisync-0.1.4 lib/apisync/http/query_string.rb
apisync-0.1.3 lib/apisync/http/query_string.rb