Module: Dommy::Rails::Stimulus

Defined in:
lib/dommy/rails/stimulus.rb

Class Method Summary collapse

Class Method Details

.action?(scope, action) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/dommy/rails/stimulus.rb', line 14

def action?(scope, action)
  scope.query_selector_all("[data-action]").to_a.any? { |element| has_action?(element, action) }
end

.controller?(scope, name) ⇒ Boolean

—– Scope-level predicates (any element in scope matches) —–

Returns:

  • (Boolean)


10
11
12
# File 'lib/dommy/rails/stimulus.rb', line 10

def controller?(scope, name)
  scope.query_selector_all("[data-controller]").to_a.any? { |element| has_controller?(element, name) }
end

.has_action?(element, action) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/dommy/rails/stimulus.rb', line 33

def has_action?(element, action)
  actions = element.get_attribute("data-action").to_s.split
  actions.any? { |a| a == action.to_s || a.end_with?("->#{action}") }
end

.has_controller?(element, name) ⇒ Boolean

—– Element-level predicates —–

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/dommy/rails/stimulus.rb', line 28

def has_controller?(element, name)
  controllers = element.get_attribute("data-controller").to_s.split
  controllers.include?(name.to_s)
end

.has_target?(element, controller, target) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/dommy/rails/stimulus.rb', line 38

def has_target?(element, controller, target)
  element.has_attribute?("data-#{controller}-target") &&
    element.get_attribute("data-#{controller}-target").to_s.split.include?(target.to_s)
end

.has_value?(element, controller, key, value) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
# File 'lib/dommy/rails/stimulus.rb', line 43

def has_value?(element, controller, key, value)
  attr_name = "data-#{controller}-#{key}-value"
  return false unless element.has_attribute?(attr_name)
  element.get_attribute(attr_name).to_s == value.to_s
end

.target?(scope, controller, target) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/dommy/rails/stimulus.rb', line 18

def target?(scope, controller, target)
  scope.query_selector_all("[data-#{controller}-target]").to_a.any? { |element| has_target?(element, controller, target) }
end

.value?(scope, controller, key, value) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/dommy/rails/stimulus.rb', line 22

def value?(scope, controller, key, value)
  scope.query_selector_all("[data-#{controller}-#{key}-value]").to_a.any? { |element| has_value?(element, controller, key, value) }
end