Sha256: a6c74b2158be40503fb492cf55ac06270673cdc4800abb1a185439eca49ea06a

Contents?: true

Size: 1.37 KB

Versions: 5

Compression:

Stored size: 1.37 KB

Contents

require 'cgi' unless defined?(CGI)

module Hungry
  module Util
    extend self

    def log(message, type = :info)
      if Hungry.logger
        message = "[Hungry] #{message}"
        Hungry.logger.send(type, message)
      end
    end

    def parse_json(json)
      Hungry.json_parser.call(json)
    end

    def params_from_uri(uri)
      uri = URI.parse(uri) unless uri.is_a?(URI)
      parse_query(uri.query) if uri.query.present?
    end

    def uri_with_params(uri, params = {})
      params = params.map { |k,v| "#{k}=#{CGI.escape(v.to_s)}" }
                     .join('&')
                     .presence

      [uri, params].compact
                   .join('?')
    end

    def is_numeric?(value)
      !!(value.to_s =~ /^[+-]?[\d]+(\.[\d]+){0,1}$/)
    end

    private

    # Copied from rack/utils:
    def unescape(s, encoding = Encoding::UTF_8)
      URI.decode_www_form_component(s, encoding)
    end

    def parse_query(qs, d = nil, &unescaper)
      unescaper ||= method(:unescape)

      params = {}

      (qs || '').split(d ? /[#{d}] */ : /[&;] */n).each do |p|
        next if p.empty?
        k, v = p.split('=', 2).map(&unescaper)

        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
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
hungry-0.2.0 lib/hungry/util.rb
hungry-0.1.5 lib/hungry/util.rb
hungry-0.1.4 lib/hungry/util.rb
hungry-0.1.3 lib/hungry/util.rb
hungry-0.1.2 lib/hungry/util.rb