Sha256: 1bfa16920805fdd1e14e0b79e365a7212627d23140ed6a9d4fe163a8be22f165

Contents?: true

Size: 1.18 KB

Versions: 5

Compression:

Stored size: 1.18 KB

Contents

require 'cgi'
require 'uri'

require 'relax/symbolic_hash'

module Relax
  # Query is used to represent the query portion of a URL. It's basically just
  # a hash, where each key/value pair is a query parameter.
  class Query < SymbolicHash
    # Converts the Query to a query string for use in a URL.
    def to_s
      keys.sort { |a, b| a.to_s <=> b.to_s }.collect do |key|
        "#{key.to_s}=#{self.class.escape_value(fetch(key))}"
      end.join('&')
    end

    class << self
      # Parses a URL and returns a Query with its query portion.
      def parse(uri)
        query = uri.query.split('&').inject({}) do |query, parameter|
          key, value = parameter.split('=', 2)
          query[unescape_value(key)] = unescape_value(value)
          query
        end
        self.new(query)
      end

      # Escapes a query parameter value.
      def escape_value(value)
        CGI.escape(value.to_s).gsub('%20', '+')
      end

      # Unescapes a query parameter value.
      def unescape_value(value)
        CGI.unescape(value)
      end
    end

    protected

    # Converts each value of the Query to a string as it's added.
    def convert_value(value)
      value.to_s
    end
  end
end

Version data entries

5 entries across 5 versions & 3 rubygems

Version Path
dbalatero-relax-0.0.7.1 lib/relax/query.rb
tylerhunt-relax-0.0.5 lib/relax/query.rb
relax-0.0.5 lib/relax/query.rb
relax-0.0.7 lib/relax/query.rb
relax-0.0.6 lib/relax/query.rb