Reputation: 2473
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
Reputation: 121000
# rubocop:disable Style/RescueModifier
def self.valid_date?(date)
Date.parse(date) rescue nil
end
# rubocop:enable Style/RescueModifier
Upvotes: 0
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