Sha256: 2d8cf52e5a0f3bc2d3ea158602ad579c03701b715af6c15a3caf47cc63a4a98e

Contents?: true

Size: 1.18 KB

Versions: 15

Compression:

Stored size: 1.18 KB

Contents

module BMC::ActiveModelTypeCast
  module Decimal
    def cast_value(value)
      if value.is_a?(String)
        super value.tr(",", ".").gsub(/[^-0-9.]/, "")
      else
        super value
      end
    end
  end

  module Date
    # rubocop:disable Style/RegexpLiteral
    SANITIZABLE_FORMATS = [
      /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/,
      /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,
    ]
    # rubocop:enable Style/RegexpLiteral

    def cast_value(value)
      if sanitizable?(value)
        super sanitize(value)
      else
        super value
      end
    end

    private

    def sanitize(value)
      value.delete(" ")
    end

    def sanitizable?(value)
      return false unless value.is_a?(String)
      sanitized = sanitize(value)
      SANITIZABLE_FORMATS.any? { |r| r =~ sanitized }
    end
  end

  module Boolean
    def cast_value(value)
      value = value.strip if value.is_a?(String)
      super value
    end
  end
end

ActiveModel::Type::Date.prepend(BMC::ActiveModelTypeCast::Date)
ActiveModel::Type::Boolean.prepend(BMC::ActiveModelTypeCast::Boolean)
ActiveModel::Type::Decimal.prepend(BMC::ActiveModelTypeCast::Decimal)
ActiveModel::Type::Float.prepend(BMC::ActiveModelTypeCast::Decimal)

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
bmc-1.4.3 lib/bmc/active_model_type_cast.rb
bmc-1.4.2 lib/bmc/active_model_type_cast.rb
bmc-1.4.1 lib/bmc/active_model_type_cast.rb
bmc-1.4.0 lib/bmc/active_model_type_cast.rb
bmc-1.3.5 lib/bmc/active_model_type_cast.rb
bmc-1.3.4 lib/bmc/active_model_type_cast.rb
bmc-1.3.3 lib/bmc/active_model_type_cast.rb
bmc-1.3.2 lib/bmc/active_model_type_cast.rb
bmc-1.3.1 lib/bmc/active_model_type_cast.rb
bmc-1.3.0 lib/bmc/active_model_type_cast.rb
bmc-1.2.1 lib/bmc/active_model_type_cast.rb
bmc-1.2.0 lib/bmc/active_model_type_cast.rb
bmc-1.1.0 lib/bmc/active_model_type_cast.rb
bmc-1.0.1 lib/bmc/active_model_type_cast.rb
bmc-1.0.0 lib/bmc/active_model_type_cast.rb