Merge pull request #299 from crystal-ameba/Sija/refactor-style-predicate-name-rule

This commit is contained in:
Sijawusz Pur Rahnama 2022-11-14 14:07:33 +01:00 committed by GitHub
commit db5eee76cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 16 deletions

View file

@ -30,7 +30,7 @@ module Ameba::Rule::Style
it "reports rule, pos and message" do it "reports rule, pos and message" do
s = Source.new %q( s = Source.new %q(
class Image class Image
def has_picture?(x) def is_valid?(x)
true true
end end
end end
@ -42,7 +42,7 @@ module Ameba::Rule::Style
issue.location.to_s.should eq "source.cr:2:3" issue.location.to_s.should eq "source.cr:2:3"
issue.end_location.to_s.should eq "source.cr:4:5" issue.end_location.to_s.should eq "source.cr:4:5"
issue.message.should eq( issue.message.should eq(
"Favour method name 'picture?' over 'has_picture?'") "Favour method name 'valid?' over 'is_valid?'")
end end
it "ignores if alternative name isn't valid syntax" do it "ignores if alternative name isn't valid syntax" do

View file

@ -1,25 +1,20 @@
module Ameba::Rule::Style module Ameba::Rule::Style
# A rule that disallows tautological predicate names, meaning those that # A rule that disallows tautological predicate names -
# start with the prefix `has_` or the prefix `is_`. Ignores if the alternative isn't valid Crystal code (e.g. `is_404?`). # meaning those that start with the prefix `is_`, except for
# the ones that are not valid Crystal code (e.g. `is_404?`).
# #
# Favour these: # Favour this:
# #
# ``` # ```
# def valid?(x) # def valid?(x)
# end # end
#
# def picture?(x)
# end
# ``` # ```
# #
# Over these: # Over this:
# #
# ``` # ```
# def is_valid?(x) # def is_valid?(x)
# end # end
#
# def has_picture?(x)
# end
# ``` # ```
# #
# YAML configuration example: # YAML configuration example:
@ -30,16 +25,14 @@ module Ameba::Rule::Style
# ``` # ```
class PredicateName < Base class PredicateName < Base
properties do properties do
enabled false
description "Disallows tautological predicate names" description "Disallows tautological predicate names"
end end
MSG = "Favour method name '%s?' over '%s'" MSG = "Favour method name '%s?' over '%s'"
def test(source, node : Crystal::Def) def test(source, node : Crystal::Def)
return unless node.name =~ /^(is|has)_(\w+)\?/ return unless node.name =~ /^is_([a-z]\w*)\?$/
alternative = $2 alternative = $1
return unless alternative =~ /^[a-z][a-zA-Z_0-9]*$/
issue_for node, MSG % {alternative, node.name} issue_for node, MSG % {alternative, node.name}
end end