File: multi_select_list.rb

package info (click to toggle)
ruby-mechanize 2.7.6-1%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,480 kB
  • sloc: ruby: 11,380; makefile: 5; sh: 4
file content (93 lines) | stat: -rw-r--r-- 1,886 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
##
# 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'

class Mechanize::Form::MultiSelectList < Mechanize::Form::Field
  extend Mechanize::ElementMatcher

  attr_accessor :options

  def initialize node
    value = []
    @options = node.search('option').map { |n|
      Mechanize::Form::Option.new(n, self)
    }

    super node, value
  end

  ##
  # :method: option_with
  #
  # Find one option on this select list with +criteria+
  #
  # Example:
  #
  #   select_list.option_with(:value => '1').value = 'foo'

  ##
  # :mehtod: option_with!(criteria)
  #
  # Same as +option_with+ but raises an ElementNotFoundError if no button
  # matches +criteria+

  ##
  # :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

  elements_with :option

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

  # Select no options
  def select_none
    @value = []
    options.each(&:untick)
  end

  # Select all options
  def select_all
    @value = []
    options.each(&:tick)
  end

  # Get a list of all selected options
  def selected_options
    @options.find_all(&:selected?)
  end

  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

  def value
    @value + selected_options.map(&:value)
  end

end