Sha256: c56ddde1de990b4c4ca3f947eb295804d65e4df6acf227ab5e0ac008a714d963

Contents?: true

Size: 1.15 KB

Versions: 38

Compression:

Stored size: 1.15 KB

Contents

class Eco::API::Common::People::DefaultParsers::NumericParser < Eco::API::Common::Loaders::Parser
  attribute :number

  def parser(value, deps)
    parse_number(value, attr: deps['attr'])
  end

  def serializer(value, _deps)
    value.is_a?(Array) ? value.map(&:to_s) : value.to_s
  end

  private

  def parse_number(value, attr:)
    return value.map {|val| parse_number(val, attr: attr)}.compact if value.is_a?(Enumerable)
    return nil if blank?(value)

    value = value.to_s.strip
    return wrong!(value, attr: attr) unless number?(value)

    value.to_f
  rescue ArgumentError, TypeError
    nil
  end

  def number?(value)
    true if Float(value)
  rescue ArgumentError, TypeError
    false
  end

  def wrong!(value, attr:, desc: "Can't make a number out of")
    return if wrong(attr).key?(value)
    wrong(attr)[value] = value
    log(:warn) { "#{desc} '#{value}' for '#{attr}'" }
    nil
  end

  def wrong(attr = nil)
    @wrong ||= {}
    return @wrong if attr.nil?
    @wrong[attr] ||= {}
  end

  def blank?(value)
    return true if value.nil?
    return true if value.to_s.strip.empty?
    false
  end
end

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
eco-helpers-3.0.1 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-3.0.0 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.25 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.24 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.23 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.22 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.21 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.20 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.19 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.18 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.17 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.16 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.15 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.14 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.13 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.12 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.4 lib/eco/api/common/people/default_parsers/numeric_parser.rb
eco-helpers-2.7.2 lib/eco/api/common/people/default_parsers/numeric_parser.rb