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, style: nil) ⇒ ViewComponentAudit

Returns a new instance of ViewComponentAudit.



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

def initialize(root:, output: $stdout, style: nil)
  @root = Pathname(root)
  @output = output
  @style = style || Report::Style.new(io: output)
end

Instance Method Details

#find_missing_previewsObject



41
42
43
44
45
# File 'lib/guardrails/view_component_audit.rb', line 41

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

#find_orphan_slotsObject



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

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



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

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