module PIM::AttributeTemplates::Physical

Public Class Methods

format(value, attribute = nil) click to toggle source
# File pim.rb, line 5457
def self.format value, attribute = nil

  return nil if value.nil? or value.empty?
  raise "Value #{PIM::Utils.value_msg(value)}cannot be transformed into a Physical value" unless PIM::Utils.is_hash?(value) and (value.length == 1 or value.length == 2)

  unit = PIM::Utils.as_json(value.keys[0])
  quantity = PIM::Utils.as_json(value.values[0])

  space = PIM::Utils.is_empty?(quantity) ? '' : ' '

  return "#{quantity}#{space}#{unit}"

end
parse(value, attribute = nil) click to toggle source
# File pim.rb, line 5398
def self.parse value, attribute = nil

  return nil if value.nil? or value.to_s.empty?
  return value if PIM::Utils.is_hash?(value)

  _, quantity, unit = value.to_s.split(/^([+-]?[\d\.,]*)\s*([\d\w]*)$/)

  quantity = (quantity || "").strip
  unit = (unit || "").strip

  if quantity.empty?
    quantity = PIM::ErrorValue.new(nil, 'Physical', "The quantity part is missing in '#{value}'")
  else

    # NOTE: 'attribute' should not be 'nil' here,
    # but unfortunately there still is some old code out there
    # which does not providing a 'attribute' parameter.
    # In this case, we need to set proper defaults!
    if attribute.nil?
      disable_value_normalization = false
      value_class = Float.to_s
    else
      disable_value_normalization = attribute.param(:disable_value_normalization)
      value_class = (attribute.param(:value_class) || Float).to_s
    end

    # Don't convert value if 'disable_value_normalization' is true
    unless disable_value_normalization

      if value_class == Integer.to_s
        converter = -> (v) {

          vFloat = PIM::Utils.to_float(v, fix_decimal_separator: true)
          vInt = PIM::Utils.to_integer(vFloat, fix_decimal_separator: true)

          return vInt unless Float(vInt) != vFloat

          raise ArgumentError.new "invalid integer value: '#{v}'"

        }
      else
        converter = -> (v) { PIM::Utils.to_float(v, fix_decimal_separator: true) }
      end

      begin
        quantity = converter.call(quantity)
      rescue => e
        quantity = PIM::ErrorValue.new(value, 'Physical', "Quantity part #{PIM::Utils.value_msg(quantity)}cannot be converted to a valid #{value_class}")
      end
    end

  end

  unit = PIM::ErrorValue.new(nil, 'Physical', "The unit part is missing in '#{value}'") if unit.empty?

  return { unit => quantity }

end