Skip to content

Instantly share code, notes, and snippets.

@NaN1488
Created March 27, 2013 17:47
Show Gist options
  • Save NaN1488/5256487 to your computer and use it in GitHub Desktop.
Save NaN1488/5256487 to your computer and use it in GitHub Desktop.
Add grouped_options_for_select_with_cache method to ActionView::Helpers::FormOptionsHelper in order to avoid recreate a html string options for the same collection
module ActionView
module Helpers
module FormOptionsHelper
#
# NOTE: This approach does not work with the :disabled flag and other HTML options that
# grouped_options_for_select_with_cache supports, it was done
# this way in order to improve the performance of large select tags that are rebuilt
# more than one time per request.
def grouped_options_for_select_with_cache(grouped_options, selected_key = nil, prompt = nil)
@grouped_options_cache ||= {}
object_id = grouped_options.object_id
body = ''
body << content_tag(:option, prompt, { :value => "" }, true) if prompt
grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
if @grouped_options_cache[object_id].nil?
@grouped_options_cache[object_id] = grouped_options.map do |group|
content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
end
@grouped_options_cache[object_id] = @grouped_options_cache[object_id].join('')
body << @grouped_options_cache[object_id]
else
selected_value = %(value="#{selected_key}")
body << @grouped_options_cache[object_id].gsub(selected_value, %(selected="selected" #{selected_value}))
end
body.html_safe
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment