class RuboCop::Cop::Style::BarePercentLiterals
%q/She said: ‘Hi’/
%Q|He said: “#{greeting}”|
# good
%/She said: ‘Hi’/
%|He said: “#{greeting}”|
# bad
@example EnforcedStyle: percent_q
%{She said: ‘Hi’}
%(He said: “#{greeting}”)
# good
%q{She said: ‘Hi’}
%Q(He said: “#{greeting}”)
# bad
@example EnforcedStyle: bare_percent (default)
Checks if usage of %() or %Q() matches configuration.
def add_offense_for_wrong_style(node, good, bad)
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
def check(node)
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
def on_dstr(node)
def on_dstr(node) check(node) end
def on_str(node)
def on_str(node) check(node) end
def requires_bare_percent?(source)
def requires_bare_percent?(source) style == :bare_percent && source.start_with?('%Q') end
def requires_percent_q?(source)
def requires_percent_q?(source) style == :percent_q && /^%[^\w]/.match?(source) end