Sha256: d4b2bc55f0c669bf85b6c1b3e99f2729a65572bd86e62abceeda6bf15c17444d

Contents?: true

Size: 1.26 KB

Versions: 37

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

module ActiveModel
  module Type
    # = Active Model \Binary \Type
    #
    # Attribute type for representation of binary data. This type is registered
    # under the +:binary+ key.
    #
    # Non-string values are coerced to strings using their +to_s+ method.
    class Binary < Value
      def type
        :binary
      end

      def binary?
        true
      end

      def cast(value)
        if value.is_a?(Data)
          value.to_s
        else
          value = super
          value = value.b if ::String === value && value.encoding != Encoding::BINARY
          value
        end
      end

      def serialize(value)
        return if value.nil?
        Data.new(super)
      end

      def changed_in_place?(raw_old_value, value)
        old_value = deserialize(raw_old_value)
        old_value != value
      end

      class Data # :nodoc:
        def initialize(value)
          value = value.to_s
          value = value.b unless value.encoding == Encoding::BINARY
          @value = value
        end

        def to_s
          @value
        end
        alias_method :to_str, :to_s

        def hex
          @value.unpack1("H*")
        end

        def ==(other)
          other == to_s || super
        end
      end
    end
  end
end

Version data entries

37 entries across 37 versions & 5 rubygems

Version Path
activemodel-8.0.0 lib/active_model/type/binary.rb
activemodel-7.2.2 lib/active_model/type/binary.rb
activemodel-7.1.5 lib/active_model/type/binary.rb
activemodel-8.0.0.rc2 lib/active_model/type/binary.rb
activemodel-7.2.1.2 lib/active_model/type/binary.rb
activemodel-7.1.4.2 lib/active_model/type/binary.rb
activemodel-8.0.0.rc1 lib/active_model/type/binary.rb
activemodel-7.2.1.1 lib/active_model/type/binary.rb
activemodel-7.1.4.1 lib/active_model/type/binary.rb
activemodel-8.0.0.beta1 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha9 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha8 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha7 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha4 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha3 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha2 lib/active_model/type/binary.rb
omg-activemodel-8.0.0.alpha1 lib/active_model/type/binary.rb
activemodel-7.1.4 lib/active_model/type/binary.rb
activemodel-7.2.1 lib/active_model/type/binary.rb
activemodel-7.2.0 lib/active_model/type/binary.rb