Class: MySQLBinUUID::Type

Inherits:
ActiveModel::Type::Binary
  • Object
show all
Defined in:
lib/mysql-binuuid/type.rb

Defined Under Namespace

Classes: Data

Instance Method Summary collapse

Instance Method Details

#cast(value) ⇒ Object

Invoked when a value that is returned from the database needs to be displayed into something readable again.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/mysql-binuuid/type.rb', line 11

def cast(value)
  if value.is_a?(MySQLBinUUID::Type::Data)
    # It could be a Data object, in which case we should add dashes to the
    # string value from there.
    add_dashes(value.to_s)
  elsif value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT && strip_dashes(value).length != 32
    # We cannot unpack something that looks like a UUID, with or without
    # dashes. Not entirely sure why ActiveRecord does a weird combination of
    # cast and serialize before anything needs to be saved..
    undashed_uuid = value.unpack1('H*')
    add_dashes(undashed_uuid.to_s)
  else
    super
  end
end

#serialize(value) ⇒ Object

Invoked when the provided value needs to be serialized before storing it to the database.



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mysql-binuuid/type.rb', line 29

def serialize(value)
  return if value.nil?
  undashed_uuid = strip_dashes(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 valid_undashed_uuid?(undashed_uuid)
    raise MySQLBinUUID::InvalidUUID, "#{value} is not a valid UUID"
  end

  Data.new(undashed_uuid)
end

#typeObject



5
6
7
# File 'lib/mysql-binuuid/type.rb', line 5

def type
  :uuid
end