Sha256: 32236de115bc4b0008614065c14a5fb32c9d11f2aefc2e2f1999589e90969c9e

Contents?: true

Size: 921 Bytes

Versions: 2

Compression:

Stored size: 921 Bytes

Contents

# frozen_string_literal: true

module Normalizy
  module Filters
    module Percent
      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?

          value = "%0.#{precision(options)}f" % [value.sub(separator(options), '.')]
          value = value.delete('.') if cents?(options)

          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('percentage.format.precision', default: 2)
        end

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
normalizy-1.0.0 lib/normalizy/filters/percent.rb
normalizy-0.2.0 lib/normalizy/filters/percent.rb