Class: ERBLint::Linters::AllowedScriptType

Inherits:
ERBLint::Linter show all
Includes:
ERBLint::LinterRegistry
Defined in:
lib/erb_lint/linters/allowed_script_type.rb

Overview

Allow ‘<script>` tags in ERB that have specific `type` attributes. This only validates inline `<script>` tags, a separate rubocop cop may be used to enforce the same rule when `javascript_tag` is called.

Defined Under Namespace

Classes: ConfigSchema

Constant Summary

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR

Instance Attribute Summary

Attributes inherited from ERBLint::Linter

#offenses

Instance Method Summary collapse

Methods included from ERBLint::LinterRegistry

find_by_name, included, load_custom_linters

Methods inherited from ERBLint::Linter

#add_offense, #clear_offenses, #enabled?, #excludes_file?, inherited, #initialize, support_autocorrect?

Constructor Details

This class inherits a constructor from ERBLint::Linter

Instance Method Details

#autocorrect(_processed_source, offense) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/erb_lint/linters/allowed_script_type.rb', line 60

def autocorrect(_processed_source, offense)
  return unless offense.context
  lambda do |corrector|
    type_attribute, = *offense.context
    if type_attribute.nil?
      corrector.insert_after(offense.source_range, ' type="text/javascript"')
    elsif !type_attribute.value.present?
      corrector.replace(type_attribute.node.loc, 'type="text/javascript"')
    end
  end
end

#run(processed_source) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/erb_lint/linters/allowed_script_type.rb', line 22

def run(processed_source)
  parser = processed_source.parser
  parser.nodes_with_type(:tag).each do |tag_node|
    tag = BetterHtml::Tree::Tag.from_node(tag_node)
    next if tag.closing?
    next unless tag.name == 'script'

    if @config.disallow_inline_scripts?
      name_node = tag_node.to_a[1]
      add_offense(
        name_node.loc,
        "Avoid using inline `<script>` tags altogether. "\
        "Instead, move javascript code into a static file."
      )
      next
    end

    type_attribute = tag.attributes['type']
    type_present = type_attribute.present? && type_attribute.value_node.present?

    if !type_present && !@config.allow_blank?
      name_node = tag_node.to_a[1]
      add_offense(
        name_node.loc,
        "Missing a `type=\"text/javascript\"` attribute to `<script>` tag.",
        [type_attribute]
      )
    elsif type_present && !@config.allowed_types.include?(type_attribute.value)
      add_offense(
        type_attribute.loc,
        "Avoid using #{type_attribute.value.inspect} as type for `<script>` tag. "\
        "Must be one of: #{@config.allowed_types.join(', ')}"\
        "#{' (or no type attribute)' if @config.allow_blank?}."
      )
    end
  end
end