Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Store a hash in form hidden fields
module FormHiddenFieldsHelper
# Originally based on http://marklunds.com/articles/one/314
def spread_param_hash(hash, key_prefix = '')
format_key = key_prefix.blank? ? lambda { |k| k.to_s } :
lambda { |k| "#{key_prefix}[#{k}]" }
flat_hash = {}
hash.each do |k, v|
k = format_key.call(k)
if v.is_a?(Hash)
flat_hash.merge!(spread_param_hash(v, k))
else
flat_hash[k] = v
end
end
flat_hash
end
def hidden_field_tags_from_hash(hash, options = {})
hidden_field_tags = []
spread_param_hash(hash).each do |name, value|
if value.is_a?(Array)
name << '[]'
value.each do |v|
hidden_field_tags << hidden_field_tag(name, v, options)
end
else
hidden_field_tags << hidden_field_tag(name, value, options)
end
end
hidden_field_tags.join("\n").html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment