Last active
August 29, 2015 13:58
-
-
Save caius/10289031 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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