Skip to content

Instantly share code, notes, and snippets.

@caius
Last active August 29, 2015 13:58
Show Gist options
  • Save caius/10289031 to your computer and use it in GitHub Desktop.
Save caius/10289031 to your computer and use it in GitHub Desktop.
# encoding: utf-8
module Rubocop
module Cop
module Style
# This cop checks for ^/$ usage in regexps and reports violations
class RegexAnchors < Cop
def on_regexp(node)
string_parts = node.children.select { |child| child.type == :str }
total_string = string_parts.map { |s| s.loc.expression.source }.join
if start_anchor?(total_string)
add_offence(node, :expression, "Use \\A rather than ^ for checking start of string")
end
if end_anchor?(total_string)
add_offence(node, :expression, "Use \\z rather than $ for checking termination of string")
end
end
private
def start_anchor?(string)
return false unless string["^"]
string.scan(/.?\^/).each do |m|
return true unless m["[^"] || m["\\^"]
end
false
end
def end_anchor?(string)
return false unless string["$"]
string.scan(/.?\$/).each do |m|
return true unless m["\\$"]
end
false
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment