Skip to content

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

@inveterateliterate

Description

@inveterateliterate

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

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions