ktec
ktec

Reputation: 2473

How can I validate a date string without rescuing the exception to keep the Rubocop HandleExceptions linter happy?

I have a string which might or might not be a valid date.

I want a clean and simple way to validate whilst keeping Rubocop happy.

# TODO: Welcome suggestions for a better way to deal with this...
# rubocop:disable HandleExceptions
def self.valid_date?(date)
  Date.parse(date)
rescue ArgumentError
end
# rubocop:enable HandleExceptions

I actually feel like this is a clean way to achieve what I need, but is there a way to resolve whilst still keeping rubocop happy?

Upvotes: 0

Views: 1053

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

# rubocop:disable Style/RescueModifier
def self.valid_date?(date)
  Date.parse(date) rescue nil
end
# rubocop:enable Style/RescueModifier

Upvotes: 0

Wikiti
Wikiti

Reputation: 1636

Add a explicit nil:

# TODO: Welcome suggestions for a better way to deal with this...
# rubocop:disable HandleExceptions
def self.valid_date?(date)
  Date.parse(date)
rescue ArgumentError
  nil
end

Otherwise, enable inline rescue in .rubocop.yml for a shorter method:

Style/RescueModifier:
  Enabled: false

Then:

# TODO: Welcome suggestions for a better way to deal with this...
# rubocop:disable HandleExceptions
def self.valid_date?(date)
  Date.parse(date) rescue nil
end

Remember, how readable is your code does not deppend on what a machine says, but what other people (i.e. a community) feel about it. Rubocop is just a tool for a quick way to review code without reading line by line manually.

Upvotes: 3

Related Questions