class RuboCop::Cop::Style::BarePercentLiterals

Checks if usage of %() or %Q() matches configuration.

@example EnforcedStyle: bare_percent (default)

# bad
%Q(He said: "#{greeting}")
%q{She said: 'Hi'}

# good
%(He said: "#{greeting}")
%{She said: 'Hi'}

@example EnforcedStyle: percent_q

# bad
%|He said: "#{greeting}"|
%/She said: 'Hi'/

# good
%Q|He said: "#{greeting}"|
%q/She said: 'Hi'/

Constants

MSG

Public Instance Methods

on_dstr(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 32
def on_dstr(node)
  check(node)
end
on_str(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 36
def on_str(node)
  check(node)
end

Private Instance Methods

add_offense_for_wrong_style(node, good, bad) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 63
def add_offense_for_wrong_style(node, good, bad)
  location = node.loc.begin

  add_offense(location, message: format(MSG, good: good, bad: bad)) do |corrector|
    source = location.source
    replacement = source.start_with?('%Q') ? '%' : '%Q'

    corrector.replace(location, source.sub(/%Q?/, replacement))
  end
end
check(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 42
def check(node)
  return if node.heredoc?
  return unless node.loc.respond_to?(:begin)
  return unless node.loc.begin

  source = node.loc.begin.source
  if requires_percent_q?(source)
    add_offense_for_wrong_style(node, 'Q', '')
  elsif requires_bare_percent?(source)
    add_offense_for_wrong_style(node, '', 'Q')
  end
end
requires_bare_percent?(source) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 59
def requires_bare_percent?(source)
  style == :bare_percent && source.start_with?('%Q')
end
requires_percent_q?(source) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 55
def requires_percent_q?(source)
  style == :percent_q && /^%[^\w]/.match?(source)
end