Class: UuidV7::Types::Base

Inherits:
ActiveModel::Type::Binary
  • Object
show all
Defined in:
lib/uuid_v7/types/base.rb

Direct Known Subclasses

MysqlType, SqliteType

Defined Under Namespace

Classes: Data

Instance Method Summary collapse

Instance Method Details

#cast(value) ⇒ Object

Type casts a value from user input (e.g. from a setter). This value may be a string from the form builder, or a ruby object passed to a setter. There is currently no way to differentiate between which source it came from.

The return value of this method will be returned from ActiveRecord::AttributeMethods::Read#read_attribute. See also: Value#cast_value.

value The raw input, as provided to the attribute setter.



24
25
26
27
28
# File 'lib/uuid_v7/types/base.rb', line 24

def cast(value)
  return unless value

  super(add_dashes(value.to_s)) # super will encode the value as binary (Encoding::BINARY)
end

#deserialize(value) ⇒ Object

ActiveModel::Type::Binary implements this method as: def deserialize(value)

cast(value)

end



62
63
64
65
66
67
68
69
70
71
# File 'lib/uuid_v7/types/base.rb', line 62

def deserialize(value)
  return unless value

  # If the value is a binary data, convert it to a hex string, and call cast(value)
  if value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT
    super(value.unpack1("H*"))
  else
    super # foward to cast(value)
  end
end

#serialize(value) ⇒ Object

Casts a value from the ruby type to a type that the database knows how to understand. The returned value from this method should be a String, Numeric, Date, Time, Symbol, true, false, or nil.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/uuid_v7/types/base.rb', line 34

def serialize(value)
  return unless value

  # To avoid SQL injection, verify that it looks like a UUID. ActiveRecord
  # does not explicity escape the Binary data type. escaping is implicit as
  # the Binary data type always converts its value to a hex string.
  unless value.match?(/\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/)
    raise InvalidUUID, "#{value} is not a valid UUID" if UuidV7.configuration.throw_invalid_uuid

    return nil
  end

  return value if value.is_a?(Data)

  Data.new(strip_dashes(value))
end

#typeObject



10
11
12
# File 'lib/uuid_v7/types/base.rb', line 10

def type
  :uuid_v7
end