class RuboCop::Cop::Style::BarePercentLiterals

This cop checks if usage of %() or %Q() matches configuration.

Constants

MSG

Public Instance Methods

on_dstr(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 11
def on_dstr(node)
  check(node)
end
on_str(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 15
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 42
def add_offense_for_wrong_style(node, good, bad)
  add_offense(node, location: :begin, message: format(MSG, good, bad))
end
autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 46
def autocorrect(node)
  src = node.loc.begin.source
  replacement = src.start_with?('%Q') ? '%' : '%Q'
  lambda do |corrector|
    corrector.replace(node.loc.begin, src.sub(/%Q?/, replacement))
  end
end
check(node) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 21
def check(node)
  return if node.loc.respond_to?(:heredoc_body)
  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 38
def requires_bare_percent?(source)
  style == :bare_percent && source =~ /^%Q/
end
requires_percent_q?(source) click to toggle source
# File lib/rubocop/cop/style/bare_percent_literals.rb, line 34
def requires_percent_q?(source)
  style == :percent_q && source =~ /^%[^\w]/
end