Created
March 2, 2009 18:34
-
-
Save julik/72900 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 NestedParams | |
NESTED_PARAM_PREFIX = /^__nested_/i | |
module ControllerClassMethods | |
def expand_nested_params | |
before_filter :handle_params #{ |c| c.expand_nested_params(c.params) } | |
end | |
end | |
module ControllerInstanceMethods | |
def handle_params | |
self.params.replace(expand_nested_params(params)) | |
if @seen_exp_params | |
logger.info "Expanded params" | |
end | |
true | |
end | |
def expand_nested_params(h) | |
h.each_pair do | k, v | | |
if k =~ NESTED_PARAM_PREFIX | |
@seen_exp_params = true | |
expanded_key = k.gsub(NESTED_PARAM_PREFIX, '') | |
expanded = CGIMethods.parse_query_parameters(v) | |
# Special case - the hash with one value which is an array must be expanded | |
# in an array neglecting the subkey | |
if expanded.is_a?(Hash) && (expanded.length == 1) && expanded[expanded.keys.first].is_a?(Array) | |
h[expanded_key] = expanded.values.pop | |
h[expanded_key] = [] if h[expanded_key].empty? | |
elsif expanded == {} | |
h[expanded_key] = [] | |
else | |
h[expanded_key] = expanded | |
end | |
h.delete(k) | |
elsif v.is_a?(Hash) | |
expand_nested_params(v) | |
end | |
end | |
return h | |
end | |
end | |
ActionController::Base.send :include, ControllerInstanceMethods | |
ActionController::Base.send :extend, ControllerClassMethods | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment