Class: Guardrails::ViewComponentAudit

Inherits:
Object
  • Object
show all
Defined in:
lib/guardrails/view_component_audit.rb

Defined Under Namespace

Classes: OrphanSlot, Result

Constant Summary collapse

COMPONENT_DIR =
"app/components"
COMPONENT_GLOB =
"**/*_component.rb"
PREVIEW_DIRS =
[
  "test/components/previews",
  "spec/components/previews"
].freeze
PREVIEW_GLOB =
"**/*_component_preview.rb"
SLOT_PATTERN =
/^\s*(renders_one|renders_many)\s+:([a-z_][\w]*)/

Instance Method Summary collapse

Constructor Details

#initialize(root:, output: $stdout) ⇒ ViewComponentAudit

Returns a new instance of ViewComponentAudit.



25
26
27
28
# File 'lib/guardrails/view_component_audit.rb', line 25

def initialize(root:, output: $stdout)
  @root = Pathname(root)
  @output = output
end

Instance Method Details

#find_missing_previewsObject



39
40
41
42
43
# File 'lib/guardrails/view_component_audit.rb', line 39

def find_missing_previews
  defined = collect_components
  previewed = collect_previews
  (defined - previewed).sort
end

#find_orphan_slotsObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/guardrails/view_component_audit.rb', line 45

def find_orphan_slots
  orphans = []
  component_files.each do |path|
    slots = parse_slot_declarations(path)
    next if slots.empty?

    template_path = template_for(path)
    template_content = template_path.exist? ? File.read(template_path, encoding: Encoding::UTF_8) : ""

    slots.each do |slot|
      next if rendered_in_template?(template_content, slot[:name])

      orphans << OrphanSlot.new(
        component: relative_component_name(path),
        slot: slot[:name],
        slot_kind: slot[:kind],
        file: path.relative_path_from(@root).to_s,
        line: slot[:line]
      )
    end
  end
  orphans
end

#runObject



30
31
32
33
34
35
36
37
# File 'lib/guardrails/view_component_audit.rb', line 30

def run
  result = Result.new(
    missing_previews: find_missing_previews,
    orphan_slots: find_orphan_slots
  )
  print_report(result)
  result
end