Class: Dommy::Rack::Locator

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/rack/locator.rb

Overview

Finds DOM elements within a document by Capybara-style locators. Pure querying: it raises ElementNotFoundError / AmbiguousElementError but does not mutate the DOM or perform navigation.

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ Locator

Returns a new instance of Locator.



9
10
11
# File 'lib/dommy/rack/locator.rb', line 9

def initialize(document)
  @document = document
end

Instance Method Details

#find_button(locator) ⇒ Object

A submit-capable button by text, value, id, name, or alt.



32
33
34
35
36
37
# File 'lib/dommy/rack/locator.rb', line 32

def find_button(locator)
  buttons = @document.query_selector_all(
    "button, input[type='submit'], input[type='image'], input[type='button']"
  )
  resolve_single(buttons.select { |b| button_matches?(b, locator) }, locator)
end

#find_field(locator) ⇒ Object

A form field by id, name, label text, placeholder, or aria-label.



14
15
16
17
18
19
20
21
22
23
# File 'lib/dommy/rack/locator.rb', line 14

def find_field(locator)
  candidates = []
  by_id = @document.get_element_by_id(locator)
  candidates << by_id if by_id
  candidates.concat(by_name(locator))
  candidates.concat(label_targets(locator))
  candidates.concat(by_field_attribute("placeholder", locator))
  candidates.concat(by_field_attribute("aria-label", locator))
  resolve_single(candidates, locator)
end

An <a> by visible text, id, title, or exact href.



26
27
28
29
# File 'lib/dommy/rack/locator.rb', line 26

def find_link(locator)
  matches = @document.query_selector_all("a").select { |a| link_matches?(a, locator) }
  resolve_single(matches, locator)
end

#find_option(select_el, value) ⇒ Object

The <option> of a select matching by visible text, then by value.



40
41
42
43
44
# File 'lib/dommy/rack/locator.rb', line 40

def find_option(select_el, value)
  options = select_el.options.to_a
  options.find { |o| o.text_content.strip == value.to_s } ||
    options.find { |o| (o.get_attribute("value") || "").to_s == value.to_s }
end

#form_for(element) ⇒ Object

The form owning an element: an explicit ‘form` attribute, else the nearest ancestor <form>.



48
49
50
51
52
53
54
55
# File 'lib/dommy/rack/locator.rb', line 48

def form_for(element)
  form_id = element.get_attribute("form")
  if form_id && !form_id.empty?
    @document.get_element_by_id(form_id)
  else
    element.closest("form")
  end
end