Class: Scryer::Rules::FrozenStringLiteralRule

Inherits:
Scryer::Rule
  • Object
show all
Defined in:
lib/scryer/style_rules/frozen_string_literal_rule.rb

Overview

Flags Ruby files with no # frozen_string_literal: true magic comment — the one deliberate, narrow style check Scryer makes (see the README's Scryer-vs-RuboCop comparison: everything else in style/lint conventions is intentionally left to RuboCop). Checked on raw source rather than the parsed sexp — a magic comment is lexical, not part of the AST — so this only needs the file's leading lines, not Ripper.sexp.

Constant Summary collapse

MAGIC_COMMENT =
/\A#\s*frozen_string_literal:\s*(true|false)\s*\z/i.freeze

Instance Attribute Summary

Attributes inherited from Scryer::Rule

#file, #sexp, #source

Instance Method Summary collapse

Methods inherited from Scryer::Rule

inherited, #initialize

Constructor Details

This class inherits a constructor from Scryer::Rule

Instance Method Details

#scanObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/scryer/style_rules/frozen_string_literal_rule.rb', line 18

def scan
  return [] if source.strip.empty?
  return [] if leading_comment_lines.any? { |line| MAGIC_COMMENT.match?(line.strip) }

  [
    finding(
      line: 1,
      message: "This file has no `# frozen_string_literal: true` magic comment — every " \
                "string literal allocates a new String object at runtime instead of reusing " \
                "a single frozen one.",
      suggested_fix: "Add `# frozen_string_literal: true` as the first line of the file " \
                      "(after a shebang line, if any) — a cheap, safe default in modern " \
                      "Ruby. If a specific literal needs to stay mutable, call `.dup` on it " \
                      "explicitly at that call site."
    )
  ]
end