Skip to content

Commit

Permalink
Update InstanceVariables linter to support :ruby filters (#545)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdelStrother authored Jan 30, 2025
1 parent c977889 commit 5835a06
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
29 changes: 27 additions & 2 deletions lib/haml_lint/linter/instance_variables.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
Expand Down Expand Up @@ -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
20 changes: 19 additions & 1 deletion spec/haml_lint/linter/instance_variables_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 5835a06

Please sign in to comment.