Class: HamlLint::Linter::SpaceBeforeScript

Inherits:
HamlLint::Linter show all
Includes:
HamlLint::LinterRegistry
Defined in:
lib/haml_lint/linter/space_before_script.rb

Overview

Checks for Ruby script in HAML templates with no space after the `=`/`-`.

Constant Summary collapse

MESSAGE_FORMAT =
'The %s symbol should have one space separating it from code'
ALLOWED_SEPARATORS =
[' ', '#'].freeze

Instance Attribute Summary

Attributes inherited from HamlLint::Linter

#lints

Instance Method Summary collapse

Methods included from HamlLint::LinterRegistry

extract_linters_from, included

Methods inherited from HamlLint::Linter

#initialize, #name, #run

Methods included from HamlVisitor

#visit, #visit_children

Constructor Details

This class inherits a constructor from HamlLint::Linter

Instance Method Details

#visit_script(node) ⇒ Object


41
42
43
44
45
46
# File 'lib/haml_lint/linter/space_before_script.rb', line 41

def visit_script(node)
  # Plain text nodes with interpolation are converted to script nodes, so we
  # need to ignore them here.
  return unless document.source_lines[node.line - 1].lstrip.start_with?('=')
  record_lint(node, MESSAGE_FORMAT % '=') if missing_space?(node)
end

#visit_silent_script(node) ⇒ Object


48
49
50
# File 'lib/haml_lint/linter/space_before_script.rb', line 48

def visit_silent_script(node)
  record_lint(node, MESSAGE_FORMAT % '-') if missing_space?(node)
end

#visit_tag(node) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/haml_lint/linter/space_before_script.rb', line 12

def visit_tag(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  # If this tag has inline script
  return unless node.contains_script?

  text = node.script.strip
  return if text.empty?

  tag_with_text = tag_with_inline_text(node)

  unless index = tag_with_text.rindex(text)
    # For tags with inline text that contain interpolation, the parser
    # converts them to inline script by surrounding them in string quotes,
    # e.g. `%p Hello #{name}` becomes `%p= "Hello #{name}"`, causing the
    # above search to fail. Check for this case by removing added quotes.
    unless (text_without_quotes = strip_surrounding_quotes(text)) &&
           (index = tag_with_text.rindex(text_without_quotes))
      return
    end
  end

  return if tag_with_text[index] == '#' # Ignore code comments

  # Check if the character before the start of the script is a space
  # (need to do it this way as the parser strips whitespace from node)
  return unless tag_with_text[index - 1] != ' '

  record_lint(node, MESSAGE_FORMAT % '=')
end