Sha256: 84206b7c93a56c454ec170b1c6283629e74f5435e7585025df2560988e04d2d4

Contents?: true

Size: 1.31 KB

Versions: 5

Compression:

Stored size: 1.31 KB

Contents

require 'cgi'

module Angelo

  class FormEncodingError < StandardError; end

  module ParamsParser

    EMPTY_JSON = '{}'
    SEMICOLON = ';'
    EQUALS = '='
    AMPERSAND = '&'

    def parse_formencoded str
      str.split(AMPERSAND).reduce(Responder.symhash) do |p, kv|
        key, value = kv.split(EQUALS).map {|s| CGI.unescape s}
        p[key] = value
        p
      end
    end

    def parse_query_string
      parse_formencoded(request.query_string || '')
    end

    def parse_post_body
      body = request.body.to_s
      qs = parse_query_string
      case
      when form_encoded?
        body = parse_formencoded body
        qs.merge! body
      when json?
        body = EMPTY_JSON if body.empty?
        body = JSON.parse body
        recurse_symhash qs.merge! body
      else
        qs
      end
    end

    def recurse_symhash h
      h.each do |k,v|
        if Hash === v
          h[k] = Responder.symhash.merge! v
          recurse_symhash h[k]
        end
      end
      h
    end

    def form_encoded?
      content_type? FORM_TYPE
    end

    def json?
      content_type? JSON_TYPE
    end

    def content_type? type
      if request.headers[CONTENT_TYPE_HEADER_KEY]
        request.headers[CONTENT_TYPE_HEADER_KEY].split(SEMICOLON).include? type
      else
        nil
      end
    end

  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
angelo-0.3.2 lib/angelo/params_parser.rb
angelo-0.3.1 lib/angelo/params_parser.rb
angelo-0.3.0 lib/angelo/params_parser.rb
angelo-0.2.4 lib/angelo/params_parser.rb
angelo-0.2.3 lib/angelo/params_parser.rb