Sha256: 6a6a82d07fe612c43af58e1113c10a698d69b4e8a6623f7d18827075a984cc4d

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true
require 'cgi'

module BitBucket
  module Utils
    module Url
      module_function

      DEFAULT_QUERY_SEP = /[&;] */n.freeze

      KEY_VALUE_SEP = '='

      def escape(s)
        CGI.escape s.to_s
      end

      def unescape(s)
        CGI.unescape s.to_s
      end

      def build_query(params)
        params.map do |k, v|
          if v.class == Array
            build_query(v.map { |x| [k, x] })
          else
            v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
          end
        end.join('&')
      end

      def parse_query(query_string)
        return '' if query_string.nil? || query_string.empty?

        params = {}

        query_string.split(DEFAULT_QUERY_SEP).each do |part|
          k, v = part.split(KEY_VALUE_SEP, 2).map { |el| unescape(el) }

          if cur = params[k]
            if cur.class == Array
              params[k] << v
            else
              params[k] = [cur, v]
            end
          else
            params[k] = v
          end
        end
        params
      end

      def parse_query_for_param(query_string, name)
        parse_query(query_string).each do |key, val|
          return val.first if (name == key) && val.is_a?(Array)
          return val if name == key
        end
        nil
      end
    end # Url
  end # Utils
end # BitBucket

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bitbuckets-0.2.0 lib/bitbucket_rest_api/utils/url.rb