-
Notifications
You must be signed in to change notification settings - Fork 441
/
missing_preview_file.rb
30 lines (24 loc) · 1.21 KB
/
missing_preview_file.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module RuboCop
module Cop
module ViewComponent
class MissingPreviewFile < RuboCop::Cop::Base
include RuboCop::Cop::RangeHelp # for source_range
def on_new_investigation
super
component_filename = File.basename(processed_source.file_path)
# Only consider Ruby files, anything else is ignored, even Haml templates ending with `.html.haml.rb`
return unless component_filename.end_with?('_component.rb')
# The ApplicationComponent should not have a preview file
return if component_filename == 'application_component.rb'
preview_filename = component_filename.gsub(/\.rb$/, '_preview.rb')
# Relative path from `Rails.root`, but we cannot use that method since it is not available inside a RuboCop cop
preview_file_relative_path = "spec/components/previews/#{preview_filename}"
preview_file = File.join(Dir.pwd, preview_file_relative_path)
return if File.exist?(preview_file)
add_offense(source_range(processed_source.buffer, 1, 0),
message: "This view component should have a preview file (`src/api/#{preview_file_relative_path}`)")
end
end
end
end
end