Skip to content

Instantly share code, notes, and snippets.

@zxiest
Created December 14, 2011 15:37
Show Gist options
  • Save zxiest/1477058 to your computer and use it in GitHub Desktop.
Save zxiest/1477058 to your computer and use it in GitHub Desktop.
Select from hash
# select_from_hash location_size
def select_from_hash(object, name, args, options={})
selected = []
include_blank = false
if (!options[:selected].nil?)
selected = options[:selected]
end
if (!options[:include_blank].nil?)
include_blank = options[:include_blank]
end
select = "<select id=\"#{object}_#{name}\" name=\"#{object}[#{name}]\">"
if include_blank == true
select += %(<option value=""></option>)
end
args.each do |arg|
is_selected = selected.include?(arg[:id])
s_selected = is_selected ? "selected='selected'" : ""
select += %(<option value="#{arg[:id]}" #{s_selected}>#{arg[:value]}</option>)
end
select += "</select>"
end
# usage in html
<%= raw select_from_hash :location, :size ,[
{ :id => 0, :value => :little},
{ :id => 1, :value => :visible},
{ :id => 2, :value => :landmark},
{ :id => 3, :value => :supermark}
], { :selected => [:little], :include_blank => true } %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment