Class: GLRubocop::GLCops::ViewComponentInheritance

Inherits:
RuboCop::Cop::Base
  • Object
show all
Defined in:
lib/gl_rubocop/gl_cops/view_component_inheritance.rb

Overview

This cop checks that all ViewComponent classes inherit from an allowlisted base class.

Good:

class ApplicationViewComponent < ViewComponent::Base
end

class ApplicationViewComponentPreview < ViewComponent::Preview
end

class Components::HeroComponent < ApplicationViewComponent
end

class Components::CardComponentPreview < ApplicationViewComponentPreview
end

class SomeHelperClass < SomeOtherClass
end

Bad:

class Components::HeroComponent
end

class Components::CardComponent < ViewComponent::Base
end

class Components::CardComponentPreview < ViewComponent::Preview
end

class Components::CardComponentPreview
end

Constant Summary collapse

COMPONENT_MSG =
'ViewComponents must inherit from ApplicationViewComponent'.freeze
PREVIEW_MSG =
'ViewComponentPreviews must inherit from ApplicationViewComponentPreview'.freeze

Instance Method Summary collapse

Instance Method Details

#component_preview_valid?(parent, class_name) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
57
# File 'lib/gl_rubocop/gl_cops/view_component_inheritance.rb', line 54

def component_preview_valid?(parent, class_name)
  class_name == 'ApplicationViewComponentPreview' ||
    parent == 'ApplicationViewComponentPreview'
end

#component_valid?(parent, class_name) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
62
# File 'lib/gl_rubocop/gl_cops/view_component_inheritance.rb', line 59

def component_valid?(parent, class_name)
  class_name == 'ApplicationViewComponent' ||
    parent == 'ApplicationViewComponent'
end

#on_class(node) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/gl_rubocop/gl_cops/view_component_inheritance.rb', line 37

def on_class(node)
  parent = node.parent_class&.const_name
  class_name = node.identifier.const_name

  if class_name.end_with?('ComponentPreview')
    return true if component_preview_valid?(parent, class_name)

    add_offense(node, message: PREVIEW_MSG)
  elsif class_name.end_with?('Component')
    return true if component_valid?(parent, class_name)

    add_offense(node, message: COMPONENT_MSG)
  else
    true
  end
end