class RuboCop::Cop::Style::PercentQLiterals

This cop checks for usage of the %Q() syntax when %q() would do.

Constants

LOWER_CASE_Q_MSG
UPPER_CASE_Q_MSG

Public Instance Methods

on_str(node) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 14
def on_str(node)
  process(node, '%Q', '%q')
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 39
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, corrected(node.source))
  end
end
correct_literal_style?(node) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 30
def correct_literal_style?(node)
  style == :lower_case_q && type(node) == '%q' ||
    style == :upper_case_q && type(node) == '%Q'
end
corrected(src) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 45
def corrected(src)
  src.sub(src[1], src[1].swapcase)
end
message(_node) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 35
def message(_node)
  style == :lower_case_q ? LOWER_CASE_Q_MSG : UPPER_CASE_Q_MSG
end
on_percent_literal(node) click to toggle source
# File lib/rubocop/cop/style/percent_q_literals.rb, line 20
def on_percent_literal(node)
  return if correct_literal_style?(node)

  # Report offense only if changing case doesn't change semantics,
  # i.e., if the string would become dynamic or has special characters.
  return if node.children != parse(corrected(node.source)).ast.children

  add_offense(node, location: :begin)
end