Home > Software design >  How to ask Rubocop to check method defined on specific class?
How to ask Rubocop to check method defined on specific class?

Time:11-10

I want to discourage the usage of notify of CustomController, but not AnotherCustomController. Is there a matcher in rubocop that allows it to check notify is from specific class?

class CustomController
   def notify(message)
      puts 'notify is deprecated'
   end
end

class AnotherCustomController
   def notify(message)
      puts message
   end
end

Currently, (send nil? :notify ...) is matched to both of them. I want to match only from CustomController.

class MatchClass < CustomController
   def run
      # This should be matched by rubocop
      notify('test')
   end
end

class NotMatchClass < AnotherCustomController
   def run
      # This shouldn't be matched by rubocop
      notify('this is another notify method')
   end
end

Thank you

CodePudding user response:

In the general case, it's not possible, because rubocop analyses things statically.

If I give you the following code, you won't be able to tell me if it should be matched or not:

class Example < SomeOtherClassYouDoNotKnow
  def run
    notify("You would need to know the definition of the parent class")
  end
end

def anywhere
  something.notify("You need to know what `something` is")
end

You could look for the particular pattern you gave but you could have both false positives and false negatives.

CodePudding user response:

I couldn't find inheritance class name, but i could find code's path. So I did like this.

node.location.expression.source_buffer.name.include?('app/jobs')

CodePudding user response:

When I want to deprecate a method and want to discourage people from using it, then I would use the Ruby StdLib Deprecate to mark it as deprecated and show a warning:

class CustomController
  extend Gem::Deprecate

  def notify(message)
    puts 'notify is deprecated'
  end
  deprecate :notify, "AnotherCustomController#notify", 2023, 11
end

class AnotherCustomController
  def notify(message)
    puts message
  end
end

Calling CustomController#notify with return a warning like this:

Customercontroller#notify is deprecated; use AnotherCustomController#notify instead. It will be removed on or after 2023-11-01.
  • Related