Sha256: 1aee5e8aea86950d2a1969be1e1cead7704888ad7a3ce33cbcb9e6c9b3ce9b18

Contents?: true

Size: 1.2 KB

Versions: 21

Compression:

Stored size: 1.2 KB

Contents

module Agilibox::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(Agilibox::ActiveModelTypeCast::Date)
ActiveModel::Type::Boolean.prepend(Agilibox::ActiveModelTypeCast::Boolean)
ActiveModel::Type::Decimal.prepend(Agilibox::ActiveModelTypeCast::Decimal)
ActiveModel::Type::Float.prepend(Agilibox::ActiveModelTypeCast::Decimal)

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
agilibox-2.0.0 lib/agilibox/active_model_type_cast.rb
agilibox-1.11.0 lib/agilibox/active_model_type_cast.rb
agilibox-1.10.5 lib/agilibox/active_model_type_cast.rb
agilibox-1.10.2 lib/agilibox/active_model_type_cast.rb
agilibox-1.10.1 lib/agilibox/active_model_type_cast.rb
agilibox-1.10.0 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.20 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.19 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.18 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.17 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.16 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.15 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.14 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.13 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.12 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.11 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.10 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.9 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.8 lib/agilibox/active_model_type_cast.rb
agilibox-1.9.7 lib/agilibox/active_model_type_cast.rb