Module: RuboCop::Cop::ViewComponent::Base

Included in:
ComponentSuffix, MissingPreview, NoGlobalState, PreferComposition, PreferPrivateMethods, PreferSlots
Defined in:
lib/rubocop/cop/view_component/base.rb

Overview

Shared helper methods for ViewComponent cops

Instance Method Summary collapse

Instance Method Details

#component_namespacesObject



43
44
45
# File 'lib/rubocop/cop/view_component/base.rb', line 43

def component_namespaces
  cop_config["ComponentNamespaces"] || []
end

#enclosing_class(node) ⇒ Object

Find the enclosing class node



48
49
50
# File 'lib/rubocop/cop/view_component/base.rb', line 48

def enclosing_class(node)
  node.each_ancestor(:class).first
end

#fully_qualified_name(node) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/rubocop/cop/view_component/base.rb', line 35

def fully_qualified_name(node)
  namespace = node.parent_module_name
  short_name = node.identifier.source
  return short_name if namespace.nil? || namespace == "Object"

  "#{namespace}::#{short_name}"
end

#inside_view_component?(node) ⇒ Boolean

Check if node is within a ViewComponent class

Returns:

  • (Boolean)


53
54
55
56
57
58
# File 'lib/rubocop/cop/view_component/base.rb', line 53

def inside_view_component?(node)
  klass = enclosing_class(node)
  return false unless klass

  view_component_class?(klass)
end

#view_component_class?(node) ⇒ Boolean

Check if a class node inherits from ViewComponent::Base or ApplicationComponent

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rubocop/cop/view_component/base.rb', line 9

def view_component_class?(node)
  return false unless node&.class_type?

  class_source = fully_qualified_name(node)
  return true if component_namespaces.any? { |ns| class_source.start_with?(ns) }

  parent_class = node.parent_class
  return false unless parent_class

  view_component_parent?(parent_class)
end

#view_component_parent?(node) ⇒ Boolean

Check if node represents a configured parent class

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/rubocop/cop/view_component/base.rb', line 22

def view_component_parent?(node)
  return false unless node.const_type?

  (cop_config["ViewComponentParentClasses"] || []).include?(node.source)
end

#view_component_parent_class?(node) ⇒ Boolean

Check if a class node is itself one of the registered parent classes.

Returns:

  • (Boolean)


29
30
31
32
33
# File 'lib/rubocop/cop/view_component/base.rb', line 29

def view_component_parent_class?(node)
  return false unless node&.class_type?

  (cop_config["ViewComponentParentClasses"] || []).include?(fully_qualified_name(node))
end