Skip to content

Instantly share code, notes, and snippets.

Created May 3, 2011 18:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
# 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 do |key, values|{|v| block_given? ? yield(key, v) : hidden_field_tag(key, v) }.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment