Skip to content

Instantly share code, notes, and snippets.

@julesfern
Created June 25, 2009 19:36
Show Gist options
  • Select an option

  • Save julesfern/136105 to your computer and use it in GitHub Desktop.

Select an option

Save julesfern/136105 to your computer and use it in GitHub Desktop.
# Splits a given parameter hash into two hashes - one containing all
# string and non-binary parameters, and one containing all file/binary parameters.
# This action is performed recursively so that:
# params = {:user=>{:attributes=>{:file=>some_file, :name=>"user name"}}, :foo=>"bar"}
# normal, multipart = split_multipart_params(params)
# normal.inspect # => {:user=>{:attributes=>{:name=>"user name"}}, :foo=>"bar"}
# multipart.inspect # => {:user=>{:attributes=>{:file=>some_file}}}
def split_multipart_params(params, *hash_path)
strings = {}
files = {}
params.each do |key, value|
if value.is_a?(Hash)
# Call recursively
s, f = split_multipart_params(value, *(hash_path+[key]))
strings = strings.deep_merge(s)
files = files.deep_merge(f)
else
# Insert it into files at the current key path if it is a binary,
# and into strings if it is not.
pwd = (value.is_a?(IO))? files : strings
hash_path.each do |component|
pwd[component] ||= {}
pwd = pwd[component]
end
pwd[key] = value
end
end
return strings, files
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment