Class: Mechanize::Form::MultiSelectList

Inherits:
Field
  • Object
show all
Defined in:
lib/mechanize/form/multi_select_list.rb

Overview

This class represents a select list where multiple values can be selected. MultiSelectList#value= accepts an array, and those values are used as values for the select list. For example, to select multiple values, simply do this:

list.value = ['one', 'two']

Single values are still supported, so these two are the same:

list.value = ['one']
list.value = 'one'

Direct Known Subclasses

SelectList

Instance Attribute Summary collapse

Attributes inherited from Field

#name

Instance Method Summary collapse

Constructor Details

#initialize(name, node) ⇒ MultiSelectList

Returns a new instance of MultiSelectList.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mechanize/form/multi_select_list.rb', line 14

def initialize(name, node)
  value = []
  @options = []

  # parse
  node.search('option').each do |n|
    option = Option.new(n, self)
    @options << option
  end
  super(name, value)
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



12
13
14
# File 'lib/mechanize/form/multi_select_list.rb', line 12

def options
  @options
end

Instance Method Details

#query_valueObject



26
27
28
# File 'lib/mechanize/form/multi_select_list.rb', line 26

def query_value
  value ? value.collect { |v| [name, v] } : ''
end

#select_allObject

Select all options



37
38
39
40
# File 'lib/mechanize/form/multi_select_list.rb', line 37

def select_all
  @value = []
  options.each { |o| o.tick }
end

#select_noneObject

Select no options



31
32
33
34
# File 'lib/mechanize/form/multi_select_list.rb', line 31

def select_none
  @value = []
  options.each { |o| o.untick }
end

#selected_optionsObject

Get a list of all selected options



43
44
45
# File 'lib/mechanize/form/multi_select_list.rb', line 43

def selected_options
  @options.find_all { |o| o.selected? }
end

#valueObject



59
60
61
62
63
64
# File 'lib/mechanize/form/multi_select_list.rb', line 59

def value
  value = []
  value.push(*@value)
  value.push(*selected_options.collect { |o| o.value })
  value
end

#value=(values) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mechanize/form/multi_select_list.rb', line 47

def value=(values)
  select_none
  [values].flatten.each do |value|
    option = options.find { |o| o.value == value }
    if option.nil?
      @value.push(value)
    else
      option.select
    end
  end
end