Sha256: ecf65ac821aca3d3ded85d09d115ef07111966eb582a42068e43ca737e18b347

Contents?: true

Size: 1.26 KB

Versions: 20

Compression:

Stored size: 1.26 KB

Contents

require 'cgi'

module Nimbu
  module Utils
    module Url
      extend self

      DEFAULT_QUERY_SEP = /[&;] */n

      KEY_VALUE_SEP = '='.freeze

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

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

      def build_query(params)
        params.map { |k, v|
          if v.class == Array
            build_query(v.map { |x| [k, x] })
          else
            v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
          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
        return nil
      end

    end # Url
  end # Utils
end # Nimbu

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
nimbu-api-0.5.0 lib/nimbu-api/utils/url.rb
nimbu-api-0.4.4 lib/nimbu-api/utils/url.rb
nimbu-api-0.4.3 lib/nimbu-api/utils/url.rb
nimbu-api-0.4.2 lib/nimbu-api/utils/url.rb
nimbu-api-0.4.1 lib/nimbu-api/utils/url.rb
nimbu-api-0.4.0 lib/nimbu-api/utils/url.rb
nimbu-api-0.3.0 lib/nimbu-api/utils/url.rb
nimbu-api-0.2.1 lib/nimbu-api/utils/url.rb
nimbu-api-0.2 lib/nimbu-api/utils/url.rb
nimbu-api-0.2.beta.3 lib/nimbu-api/utils/url.rb
nimbu-api-0.2.beta.2 lib/nimbu-api/utils/url.rb
nimbu-api-0.2.beta.1 lib/nimbu-api/utils/url.rb
nimbu-api-0.2.beta lib/nimbu-api/utils/url.rb
nimbu-api-0.1.5 lib/nimbu-api/utils/url.rb
nimbu-api-0.1.4 lib/nimbu-api/utils/url.rb
nimbu-api-0.1.3 lib/nimbu-api/utils/url.rb
nimbu-api-0.1.1 lib/nimbu-api/utils/url.rb
nimbu-api-0.1 lib/nimbu-api/utils/url.rb
nimbu-api-0.0.2 lib/nimbu-api/utils/url.rb
nimbu-api-0.0.1 lib/nimbu-api/utils/url.rb