Sha256: 89ba9535a9697e30d8c17374df07d05b7e5ff250b15cc0fc3ca270844c16b6ad

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true

module Normalizy
  module Filters
    module Money
      class << self
        def call(input, options = {})
          return input unless input.is_a?(String)

          value = input.gsub(/[^[0-9]#{separator(options)}]/, '')

          return nil if value.blank?

          if cents?(options)
            if value.include? separator(options)
              value = precisioned(value, options).delete('.')
            end
          else
            value = precisioned(value, options)
          end

          return value.send(options[:cast]) if options[:cast]

          value
        end

        private

        def cents?(options)
          options[:type]&.to_sym == :cents
        end

        def precision(options)
          options.fetch :precision, I18n.t('currency.format.precision', default: 2)
        end

        def precisioned(value, options)
          "%0.#{precision(options)}f" % [value.sub(separator(options), '.')]
        end

        def separator(options)
          options.fetch :separator, I18n.t('currency.format.separator', default: '.')
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
normalizy-1.0.1 lib/normalizy/filters/money.rb