From f79495ea4a3708c81ec3742ebbd4d5960f738c5a Mon Sep 17 00:00:00 2001 From: Jonathan del Strother Date: Thu, 30 Jan 2025 13:02:15 +0000 Subject: [PATCH] Update InstanceVariables linter to support :ruby filters --- CHANGELOG.md | 2 ++ lib/haml_lint/linter/instance_variables.rb | 29 +++++++++++++++++-- .../linter/instance_variables_spec.rb | 20 ++++++++++++- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bfcb36b..e02c99d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # HAML-Lint Changelog +* Update `InstanceVariables` linter to support :ruby filters + ### 0.59.0 * Speed up load time by preferring `require_relative` in internal gem file loading diff --git a/lib/haml_lint/linter/instance_variables.rb b/lib/haml_lint/linter/instance_variables.rb index 57ca0059..0e354a6a 100644 --- a/lib/haml_lint/linter/instance_variables.rb +++ b/lib/haml_lint/linter/instance_variables.rb @@ -21,7 +21,7 @@ def visit_script(node) return unless enabled? if node.parsed_script.contains_instance_variables? - record_lint(node, "Avoid using instance variables in #{file_types} views") + record_lint(node, failure_message) end end @@ -41,10 +41,27 @@ def visit_tag(node) visit_script(node) || if node.parsed_attributes.contains_instance_variables? - record_lint(node, "Avoid using instance variables in #{file_types} views") + record_lint(node, failure_message) end end + # Checks for instance variables in :ruby filters when the linter is enabled. + # + # @param [HamlLint::Tree::FilterNode] + # @return [void] + def visit_filter(node) + return unless enabled? + return unless node.filter_type == 'ruby' + return unless ast = parse_ruby(node.text) + + ast.each_node do |i| + if i.type == :ivar + record_lint(node, failure_message) + break + end + end + end + private # Tracks whether the linter is enabled for the file. @@ -75,5 +92,13 @@ def file_types def matcher @matcher ||= Regexp.new(config['matchers'][file_types] || '\A_.*\.haml\z') end + + # The error message when an ivar is found + # + # @api private + # @return [String] + def failure_message + "Avoid using instance variables in #{file_types} views" + end end end diff --git a/spec/haml_lint/linter/instance_variables_spec.rb b/spec/haml_lint/linter/instance_variables_spec.rb index 2d7585c9..4890defe 100644 --- a/spec/haml_lint/linter/instance_variables_spec.rb +++ b/spec/haml_lint/linter/instance_variables_spec.rb @@ -4,7 +4,14 @@ include_context 'linter' context 'when the file name does not match the matcher' do - let(:haml) { '%p= @greeting' } + let(:haml) do + [ + '%p= @greeting', + '%p{ title: @greeting }', + ':ruby', + ' x = @greeting' + ].join("\n") + end it { should_not report_lint } end @@ -222,6 +229,17 @@ it { should report_lint line: 2 } end + + context 'in a :ruby filter' do + let(:haml) do + [ + ':ruby', + ' foo = @greeting', + ].join("\n") + end + + it { should report_lint line: 1 } + end end end