Sha256: b6b7d61b1602c6617928070dffdf77097a70dbeb1e075a714eef8067d415a353

Contents?: true

Size: 1.18 KB

Versions: 15

Compression:

Stored size: 1.18 KB

Contents

require 'cgi'

module Angelo

  class FormEncodingError < StandardError; end

  module ParamsParser

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

    def parse_formencoded str
      raise FormEncodingError unless str.empty? or str.index EQUALS
      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
        qs.merge! body
      else
        qs
      end
    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

15 entries across 15 versions & 1 rubygems

Version Path
angelo-0.1.15 lib/angelo/params_parser.rb
angelo-0.1.14 lib/angelo/params_parser.rb
angelo-0.1.13 lib/angelo/params_parser.rb
angelo-0.1.12 lib/angelo/params_parser.rb
angelo-0.1.11 lib/angelo/params_parser.rb
angelo-0.1.10 lib/angelo/params_parser.rb
angelo-0.1.9 lib/angelo/params_parser.rb
angelo-0.1.8 lib/angelo/params_parser.rb
angelo-0.1.7 lib/angelo/params_parser.rb
angelo-0.1.6 lib/angelo/params_parser.rb
angelo-0.1.5 lib/angelo/params_parser.rb
angelo-0.1.4 lib/angelo/params_parser.rb
angelo-0.1.3 lib/angelo/params_parser.rb
angelo-0.1.2 lib/angelo/params_parser.rb
angelo-0.1.1 lib/angelo/params_parser.rb