Class: Mechanize::Form::MultiSelectList

Inherits:
Field
  • Object
show all
Extended by:
ElementMatcher
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, #node, #type

Instance Method Summary collapse

Methods included from ElementMatcher

elements_with

Methods inherited from Field

#<=>, #dom_class, #dom_id

Constructor Details

#initialize(node) ⇒ MultiSelectList

Returns a new instance of MultiSelectList.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mechanize/form/multi_select_list.rb', line 20

def initialize node
  value = []
  @options = []

  # parse
  node.search('option').each do |n|
    @options << Mechanize::Form::Option.new(n, self)
  end

  super node, value
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



18
19
20
# File 'lib/mechanize/form/multi_select_list.rb', line 18

def options
  @options
end

Instance Method Details

#optionObject

:method: options_with

Find all options on this select list with criteria

Example:

select_list.options_with(:value => /1|2/).each do |field|
  field.value = '20'
end


52
# File 'lib/mechanize/form/multi_select_list.rb', line 52

elements_with :option

#query_valueObject



54
55
56
# File 'lib/mechanize/form/multi_select_list.rb', line 54

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

#select_allObject

Select all options



65
66
67
68
# File 'lib/mechanize/form/multi_select_list.rb', line 65

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

#select_noneObject

Select no options



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

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

#selected_optionsObject

Get a list of all selected options



71
72
73
# File 'lib/mechanize/form/multi_select_list.rb', line 71

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

#valueObject



87
88
89
90
91
92
# File 'lib/mechanize/form/multi_select_list.rb', line 87

def value
  value = []
  value.concat @value
  value.concat selected_options.map { |o| o.value }
  value
end

#value=(values) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/mechanize/form/multi_select_list.rb', line 75

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