Skip to content

Instantly share code, notes, and snippets.

@squarism
Created July 27, 2012 17:07
Show Gist options
  • Save squarism/3189195 to your computer and use it in GitHub Desktop.
Save squarism/3189195 to your computer and use it in GitHub Desktop.
serialize rails form to mongoid or json
require 'pp'
# this is what the rails POST form params look like
have = {
"concert"=>"yanni",
"description"=>"an epic soundscape about oceans and stuff",
"set_list"=>{
"0"=>{
"set_list"=>"opener",
"energy"=>"high",
"video_wall"=>"mostly birds",
"songs"=>{
"0"=>"paths on water", "1"=>"dance with a stranger"
}
},
"1"=>{
"set_list"=>"encore",
"energy"=>"low",
"video_wall"=>"flying toasters",
"songs"=>{
"0"=>"farewell"
}
}
}
}
want = {
concert: "yanni",
description: "an epic soundscape about oceans and stuff",
set_list: [
{
set_list: "opener",
energy: "high",
video_wall: "mostly birds",
songs: [ "paths on water", "dance with a stranger" ]
},
{
set_list: "encore",
energy: "low",
video_wall: "flying toasters",
songs: [ "farewell" ]
}
]
}
# helper
def is_a_number?(string)
string.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
# the magic method
def serialize_params(original, serialized={})
if original.respond_to?(:keys)
original.keys.each do |key|
current_attribute = original[key]
if current_attribute.respond_to?(:keys)
if serialized[key.to_sym].nil?
serialized[key.to_sym] = Array.new
end
current_attribute.each do |i|
# form params have numbers as keys, if nested forms recurse
if (is_a_number?(i[0]) && i[1].class != String)
# recurse
serialized[key.to_sym] << serialize_params(i[1])
elsif i[1].class == String
# handles arrays of forms (like codes)
serialized[key.to_sym] << i[1]
end
end
else
# assign regular attribute
serialized[key.to_sym] = current_attribute
end
end
return serialized
end
end
got = serialize_params(have)
# the test that would go into minitest
puts "does this work?: #{got == want}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment