Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flag to allow Integer Parser to coerce nils / empty strings to 0 #130

Open
inveterateliterate opened this issue Jun 23, 2022 · 2 comments
Open
Assignees

Comments

@inveterateliterate
Copy link
Contributor

inveterateliterate commented Jun 23, 2022

Feature Description

since nil.to_i and ''.to_i coerce to 0, that might come in handy and would be nice to allow decanter to handle that rather than adding custom logic.

Suggested Solution

Also generally the IntegerParser may need to be refactored a bit but a simple update could be something like

  apple_count, :integer, coerce: true
...

module Decanter
  module Parser
    class IntegerParser < ValueParser
      REGEX = /(\d|[.]|[-])/

      allow Integer

      parser do |val, options|
        raise Decanter::ParseError.new 'Expects a single value' if val.is_a? Array

        return val&.to_i if options[:coerce] ==> something like this above the rest of the logic (nil does not implement `scan`)

        next if (val.nil? || val === '')

        val.is_a?(Float) ?
          val.to_i :
          val.scan(REGEX).join.try(:to_i)
      end
    end
  end
end

Alternatives Considered / Existing Workarounds

  • Custom parser

Additional Context

  • N/A
@chawes13
Copy link
Contributor

SGTM. Would you like this to be assigned to you?

@inveterateliterate
Copy link
Contributor Author

sure 😁

@inveterateliterate inveterateliterate self-assigned this Jul 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants