Created
December 5, 2011 13:25
-
-
Save codesnik/1433578 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module DotParams | |
class Middleware | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
reparse_query(env["rack.request.query_hash"]) | |
reparse_query(env["rack.request.form_hash"]) | |
@app.call(env) | |
end | |
def reparse_query params | |
return unless params | |
params.each do |key, value| | |
normalize_params params, key, value | |
end | |
end | |
def normalize_params(params, name, v = nil) | |
name =~ %r(\A[\[\]\.]*([^\[\]\.]+)\]*) | |
k = $1 || '' | |
after = $' || '' | |
return if k.empty? | |
if after == "" | |
params[k] = v | |
elsif after == "[]" || after == "." | |
params[k] ||= [] | |
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) | |
params[k] << v | |
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$) || after =~ %r(^\.\.(.+)$) | |
child_key = $1 | |
params[k] ||= [] | |
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) | |
if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key) | |
normalize_params(params[k].last, child_key, v) | |
else | |
params[k] << normalize_params({}, child_key, v) | |
end | |
else | |
params[k] ||= {} | |
raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Hash) | |
params[k] = normalize_params(params[k], after, v) | |
end | |
return params | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment