From 0b6476e4ce78a8baa537370b5fad7b8aed707912 Mon Sep 17 00:00:00 2001 From: SengMing Tan Date: Sat, 24 Nov 2018 17:41:09 -0500 Subject: [PATCH] add rubocop cop to prevent the safe navigation operator Close #596 --- .rubocop.yml | 1 + app/helpers/users_helper.rb | 10 +++++-- .../cop/style/disallow_safe_navigation.rb | 27 +++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 extras/rubocop/cop/style/disallow_safe_navigation.rb diff --git a/.rubocop.yml b/.rubocop.yml index cbc2d0fc..a6f3fdae 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,4 +1,5 @@ # Project setup: +require: ./extras/rubocop/cop/style/disallow_safe_navigation Rails: Enabled: true AllCops: diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb index 71542711..34dba763 100644 --- a/app/helpers/users_helper.rb +++ b/app/helpers/users_helper.rb @@ -9,7 +9,7 @@ module UsersHelper capture do concat link_to(stories_displayed, "/newest/#{showing_user.username}") - concat(" (+#{stories_deleted} deleted)") if @user&.is_moderator? && stories_deleted > 0 + concat(" (+#{stories_deleted} deleted)") if user_is_moderator? && stories_deleted > 0 if tag concat ", most commonly tagged " @@ -24,9 +24,15 @@ module UsersHelper capture do concat link_to(showing_user.comments_posted_count, "/threads/#{showing_user.username}") - if @user&.is_moderator? && comments_deleted > 0 + if user_is_moderator? && comments_deleted > 0 concat " (+#{comments_deleted} deleted)" end end end + +private + + def user_is_moderator? + @user && @user.is_moderator? + end end diff --git a/extras/rubocop/cop/style/disallow_safe_navigation.rb b/extras/rubocop/cop/style/disallow_safe_navigation.rb new file mode 100644 index 00000000..c7b9aaf5 --- /dev/null +++ b/extras/rubocop/cop/style/disallow_safe_navigation.rb @@ -0,0 +1,27 @@ +module RuboCop + module Cop + module Style + # The "safe navigation" operator &. makes it easier to work with and + # propagate nil values. This will disallow the use of the safe navigation + # operator + # + # @example + # + # # bad + # foo&.bar + # a.foo&.bar + # + class DisallowSafeNavigation < Cop + extend TargetRubyVersion + + MSG = 'Do not use &.'.freeze + + minimum_target_ruby_version 2.3 + + def on_csend(node) + add_offense(node) + end + end + end + end +end