class RuboCop::Cop::Style::PercentQLiterals
%Q{They all said: ‘Hooray!’}
%Q/Mix the foo into the baz./
# good
%q{They all said: ‘Hooray!’}
%q/Mix the foo into the baz./
# bad
# The ‘upper_case_q` style requires the sole use of `%Q`.
@example EnforcedStyle: upper_case_q
%q(They all said: ’Hooray!‘)
%q[Mix the foo into the baz]
# good
%Q(They all said: ’Hooray!‘)
%Q[Mix the foo into the baz.]
# bad
# interpolation is needed.
# The `lower_case_q` style prefers `%q` unless
@example EnforcedStyle: lower_case_q (default)
This cop checks for usage of the %Q() syntax when %q() would do.
def correct_literal_style?(node)
def correct_literal_style?(node) style == :lower_case_q && type(node) == '%q' || style == :upper_case_q && type(node) == '%Q' end
def corrected(src)
def corrected(src) src.sub(src[1], src[1].swapcase) end
def message(_range)
def message(_range) style == :lower_case_q ? LOWER_CASE_Q_MSG : UPPER_CASE_Q_MSG end
def on_percent_literal(node)
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. ast = ProcessedSource.new(corrected(node.source), target_ruby_version).ast return if node.children != ast.children add_offense(node.loc.begin) do |corrector| corrector.replace(node, corrected(node.source)) end end
def on_str(node)
def on_str(node) process(node, '%Q', '%q') end