0

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?

ktec
  • 2,453
  • 3
  • 26
  • 32

2 Answers2

3

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.

Wikiti
  • 1,626
  • 13
  • 21
  • 1
    It seems there's no way other than disabling Rubocop in this instance - the RescueModifier is a lesser cop to disable so that feels better thanks. I do understand what the tool is there for, I was just hoping there might be a nice way to parse a date without having an exception thrown at me. I'll give you the accepted for providing a thoughtful response anyway. – ktec Jul 01 '16 at 19:01
0
# rubocop:disable Style/RescueModifier
def self.valid_date?(date)
  Date.parse(date) rescue nil
end
# rubocop:enable Style/RescueModifier
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160