Skip to content

Instantly share code, notes, and snippets.

@mdchaney
Created September 17, 2024 23:19
Show Gist options
  • Save mdchaney/ceaddd126bdf02d557b042a0600750aa to your computer and use it in GitHub Desktop.
Save mdchaney/ceaddd126bdf02d557b042a0600750aa to your computer and use it in GitHub Desktop.
Turn an arbitrary hash into hidden fields on a Rails form
module HashFieldsHelper
def flatten_hash(hash, ancestor_names = [])
hash.map do |k, v|
case v
when Hash
flatten_hash(v, ancestor_names + [k])
when Array
v.map { |item| flatten_hash(item, ancestor_names + [k, '']) }.inject(:merge)
else
{flat_hash_key(ancestor_names + [k]) => v.to_s}
end
end.inject(:merge)
end
def flat_hash_key(names)
names.first + names[1..-1].map { "[#{_1}]" }.join
end
def hash_as_hidden_fields(hash, ancestor_names = [])
flatten_hash(hash, ancestor_names).map do |name, value|
hidden_field_tag(name, value.to_s, id: nil)
end.join("\n").html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment