Skip to content

Instantly share code, notes, and snippets.

@JonCrawford
Created September 8, 2008 23:18
Show Gist options
  • Save JonCrawford/9567 to your computer and use it in GitHub Desktop.
Save JonCrawford/9567 to your computer and use it in GitHub Desktop.
## Tests
def test_grouped_options_for_select_with_array
assert_dom_equal(
"<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
grouped_options_for_select([
["North America",
[['United States','US'],"Canada"]],
["Europe",
[["Great Britain","GB"], "Germany"]]
])
)
end
def test_grouped_options_for_select_with_selected_and_prompt
assert_dom_equal(
"<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...")
)
end
def test_optgroups_with_with_options_with_hash
assert_dom_equal(
"<optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup><optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup>",
grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']})
)
end
def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
str = String.new
unless prompt.nil?
prompt.kind_of?(String) ? prompt : 'Please select'
str += content_tag :option, prompt, :value => ""
end
grouped_options = grouped_options.sort if grouped_options.is_a? Hash
for group in grouped_options
str += content_tag :optgroup, options_for_select(group[1], selected_key), :label => group[0]
end
str
end
# Sample usage (Array):
# grouped_options = [
# ['North America',
# ['United States','Canada']],
# ['Europe',
# ['Denmark','Germany','France']]
# ]
# grouped_options_for_select(grouped_options)
#
# Sample usage (Hash):
# grouped_options = {
# 'North America' => ['United States', 'Canada'],
# 'Europe' => ['Denmark','Germany','France']
# }
# grouped_options_for_select(grouped_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment