class Bithex::Type

Serializes hex string to bit string and vice versa

Attributes

attr[R]
subtype[R]

Public Class Methods

new(attr, subtype) click to toggle source
# File lib/bithex/type.rb, line 7
def initialize(attr, subtype)
  @attr     = attr
  @subtype  = subtype
  validate_subtype
end

Public Instance Methods

assert_valid_value(value) click to toggle source
# File lib/bithex/type.rb, line 33
def assert_valid_value(value)
  return if value.blank?

  validate_format(value)
  validate_length(value)
end
deserialize(value) click to toggle source
# File lib/bithex/type.rb, line 17
def deserialize(value)
  return if value.blank?

  format("%0#{hex_value_length}x", value.to_i(2))
end
Also aliased as: type_cast_from_database
serialize(value) click to toggle source
# File lib/bithex/type.rb, line 25
def serialize(value)
  return if value.blank?

  [value.to_s].pack('H*').unpack('B*')[0]
end
Also aliased as: type_cast_for_database
type() click to toggle source
# File lib/bithex/type.rb, line 13
def type
  :bithex
end
type_cast_for_database(value)
Alias for: serialize
type_cast_from_database(value)
Alias for: deserialize

Private Instance Methods

hex_value_length() click to toggle source
# File lib/bithex/type.rb, line 42
def hex_value_length
  subtype.limit / 4
end
validate_format(value) click to toggle source
# File lib/bithex/type.rb, line 53
def validate_format(value)
  return if value =~ /\h+/

  raise ArgumentError,
        "Expected '#{value}' to be a hex string"
end
validate_length(value) click to toggle source
# File lib/bithex/type.rb, line 60
def validate_length(value)
  return if value.to_s.length == hex_value_length

  raise ArgumentError,
        "Expected length of '#{value}' to be equal to #{hex_value_length}"
end
validate_subtype() click to toggle source
# File lib/bithex/type.rb, line 46
def validate_subtype
  return if subtype.is_a?(::ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bit)

  raise ::ActiveRecord::SerializationTypeMismatch,
        "Expected '#{attr}' to be a bit string. Check DB column type."
end