Class: Bureaucrat::Widgets::Select

Inherits:
Widget
  • Object
show all
Defined in:
lib/bureaucrat/widgets.rb

Direct Known Subclasses

NullBooleanSelect, SelectMultiple

Constant Summary

Constants included from Utils

Utils::ESCAPES

Instance Attribute Summary collapse

Attributes inherited from Widget

#attrs

Instance Method Summary collapse

Methods inherited from Widget

#build_attrs, #has_changed?, #hidden?, id_for_label, inherited, #initialize_copy, #media, #value_from_datahash

Methods included from Utils

conditional_escape, escape, flatatt, format_string, make_bool, make_float, mark_safe, pretty_name, security_hash

Constructor Details

#initialize(attrs = nil, choices = []) ⇒ Select

Returns a new instance of Select.



297
298
299
300
# File 'lib/bureaucrat/widgets.rb', line 297

def initialize(attrs=nil, choices=[])
  super(attrs)
  @choices = choices.collect
end

Instance Attribute Details

#choicesObject

Returns the value of attribute choices.



295
296
297
# File 'lib/bureaucrat/widgets.rb', line 295

def choices
  @choices
end

Instance Method Details

#render(name, value, attrs = nil, choices = []) ⇒ Object



302
303
304
305
306
307
308
309
310
# File 'lib/bureaucrat/widgets.rb', line 302

def render(name, value, attrs=nil, choices=[])
  value = '' if value.nil?
  final_attrs = build_attrs(attrs, :name => name)
  output = ["<select#{flatatt(final_attrs)}>"]
  options = render_options(choices, [value])
  output << options if options && !options.empty?
  output << '</select>'
  mark_safe(output.join("\n"))
end

#render_option(option_value, option_label, selected_choices) ⇒ Object



331
332
333
334
335
# File 'lib/bureaucrat/widgets.rb', line 331

def render_option(option_value, option_label, selected_choices)
  option_value = option_value.to_s
  selected_html = selected_choices.include?(option_value) ? ' selected="selected"' : ''
  "<option value=\"#{escape(option_value)}\"#{selected_html}>#{conditional_escape(option_label.to_s)}</option>"
end

#render_options(choices, selected_choices) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/bureaucrat/widgets.rb', line 312

def render_options(choices, selected_choices)
  selected_choices = selected_choices.map(&:to_s).uniq
  output = []
  (@choices + choices).each do |option_value, option_label|
      if option_label.is_a?(Array)
        output << '<optgroup label="%s">' % escape(option_value.to_s)
        option_label.each do |option|
          val, label = option
          output << render_option(val, label, selected_choices)
        end
        output << '</optgroup>'
      else
        output << render_option(option_value, option_label,
                                selected_choices)
      end
    end
  output.join("\n")
end