Class: GLRubocop::GLCops::TextAndContentVariableNaming

Inherits:
RuboCop::Cop::Cop
  • Object
show all
Includes:
ErbContentHelper
Defined in:
lib/gl_rubocop/gl_cops/text_and_content_variable_naming.rb

Overview

Ensures that simple variable references inside text-containing HTML elements in ERB files are named with a _text or _content suffix (or are exactly ‘text` or `content`). This makes the intent explicit: _text for plain strings, _content for text-or-HTML values.

Configuration parameters that are not rendered as user-visible text (e.g. variant, size, href) belong in non-text elements and are exempt.

Good:

<p><%= @message_text %></p>
<span><%= @banner_content %></span>
<h1><%= text %></h1>
<p class="<%= @variant %>"><%= @label_text %></p>   (variant is in attribute, not body)

Bad:

<p><%= @message %></p>
<span><%= @title %></span>

Constant Summary collapse

MSG =
'`%<name>s` (line %<line>d) is rendered inside a text element. ' \
'Rename it with a `_text` suffix (plain text) or `_content` suffix (HTML content).'
TEXT_TAGS =
%w[
  a span strong em b i p
  h1 h2 h3 h4 h5 h6
  blockquote li td th
  label button dt dd caption
].freeze
BARE_VAR_PATTERN =

Matches only bare variable/ivar references: <%= @name %> or <%= name %> Does NOT match method calls with arguments (t(‘key’), helper.method, etc.)

/<%=\s*@?(\w+)\s*%>/

Instance Method Summary collapse

Methods included from ErbContentHelper

#erb_file?, #read_erb_file

Instance Method Details

#investigate(processed_source) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/gl_rubocop/gl_cops/text_and_content_variable_naming.rb', line 41

def investigate(processed_source)
  return unless erb_file?

  content = read_erb_file
  return unless content

  find_and_report_improperly_named_variables(content, processed_source)
end