Sha256: c53ff86273049c97ac5cbbab2ef599c5677084c0c6b3ac37809e51be3172e3ec

Contents?: true

Size: 592 Bytes

Versions: 2

Compression:

Stored size: 592 Bytes

Contents

# frozen_string_literal: true

module ActiveFields
  module Casters
    class DecimalCaster < BaseCaster
      def serialize(value)
        # Decimals should be saved as strings to avoid potential precision loss when stored in JSON
        cast(value)&.to_s
      end

      def deserialize(value)
        cast(value)
      end

      private

      def cast(value)
        casted = BigDecimal(value, 0, exception: false)
        casted = casted.truncate(precision) if casted && precision

        casted
      end

      def precision
        options[:precision]
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_fields-1.1.0 lib/active_fields/casters/decimal_caster.rb
active_fields-1.0.0 lib/active_fields/casters/decimal_caster.rb