lib/angelo/params_parser.rb in angelo-0.3.3 vs lib/angelo/params_parser.rb in angelo-0.4.0

- old
+ new

@@ -7,11 +7,11 @@ module ParamsParser EMPTY_JSON = '{}' def parse_formencoded str - str.split(AMPERSAND).reduce(Responder.symhash) do |p, kv| + str.split(AMPERSAND).reduce(SymHash.new) do |p, kv| key, value = kv.split(EQUALS).map {|s| CGI.unescape s} p[key] = value p end end @@ -20,32 +20,22 @@ parse_formencoded(request.query_string || EMPTY_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 + parse_formencoded body + when json? && !body.empty? + SymHash.new JSON.parse 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 + def parse_query_string_and_post_body + parse_query_string.merge! parse_post_body end def form_encoded? content_type? FORM_TYPE end @@ -57,9 +47,35 @@ 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 + + class SymHash < Hash + + # Returns a Hash that allows values to be fetched with String or + # Symbol keys. + def initialize h = nil + super(){|hash,key| hash[key.to_s] if Symbol === key} + unless h.nil? + merge! h + + # Replace values that are Hashes with SymHashes, recursively. + each do |k,v| + self[k] = case v + when Hash + SymHash.new(v) + when Array + v.map {|e| Hash === e ? SymHash.new(e) : e} + else + v + end + end + end end end