Skip to content

Instantly share code, notes, and snippets.

@toretore
Created May 3, 2011 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toretore/953941 to your computer and use it in GitHub Desktop.
Save toretore/953941 to your computer and use it in GitHub Desktop.
# Returns a set of hidden fields for params passed in the query string such that they are passed
# along with the form. Mostly for use with GET forms like search/filtering where you want to retain
# other state while adding another (<existing params>&q=pr0n)
#
# Options:
#
# :skip - An array of keys to leave out - Only works for first-level keys, i.e. not 'bar' in foo[bar]=baz
def hidden_fields_from_params(opts={})
#Use CGI.parse to get "raw" parameters that haven't been converted into arrays
#and hashes yet. This means it only has to concern itself with the one dimension
#in a query string and not the extra logic added on top with the use of [] and [foo].
CGI.parse(request.query_string).reject do |key, values|
opts[:skip].include?(key.gsub(/\[[^\]]*\]/, '')) #Remove [] and [foo] before comparing
end.map do |key, values|
values.map{|v| block_given? ? yield(key, v) : hidden_field_tag(key, v) }.join
end.join.html_safe
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment