Skip to content

Commit

Permalink
[Vmdb::Settings::Validator] Add .integer_with_method?
Browse files Browse the repository at this point in the history
This tests that a value in the settings is in fact a integer, or a
integer that can be evaluated via `.to_i_with_method` to something you
would expect.

This becomes challenging because `.to_i` by default will take any
string and convert it to zero.  This means that:

  irb> "".to_i == 0
  true
  irb> "Five".to_i == 0
  true
  irb> "Foobar".to_i == 0
  true

Hence the complexity of the method, since it requires checking that:

- it is something that is a reasonable to expect for an int
- zero when explicitly asked for
- a blank value
  • Loading branch information
NickLaMuro committed Jun 16, 2021
1 parent ce672d2 commit 2829e08
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/vmdb/settings/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,23 @@ def validate

private

def integer_with_method?(num)
if is_integer?(num.to_i_with_method) && num.present?
# handling the "Five".to_i == 0 case
#
# Allows:
#
# - 0
# - 0.minutes (always will be zero)
# - any integer
# - any integer + method
#
num.to_i_with_method != 0 || num.to_s.match?(/^0(?=\..*|$)/)
else
num.blank?
end
end

def webservices(data)
valid, errors = true, []

Expand Down

0 comments on commit 2829e08

Please sign in to comment.