Class: ActiveRecordUuid::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_uuid/serializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ Serializer



4
5
6
# File 'lib/active_record_uuid/serializer.rb', line 4

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/active_record_uuid/serializer.rb', line 3

def type
  @type
end

Instance Method Details

#dump(value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/active_record_uuid/serializer.rb', line 31

def dump(value)
  uuid = begin
    UUIDTools::UUID.parse(value)
  rescue ArgumentError, TypeError
    nil
  end

  case type
  when :binary
    uuid.raw
  when :base64
    Base64.encode64(uuid.raw).strip
  when :hexdigest
    uuid.hexdigest
  when :string
    uuid.to_s
  end
end

#load(value) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/active_record_uuid/serializer.rb', line 8

def load(value)
  return nil if value.nil?

  begin
    uuid = case type
    when :binary
      UUIDTools::UUID.parse_raw(value)
    when :base64
      UUIDTools::UUID.parse_raw(Base64.decode64(value))
    when :hexdigest
      UUIDTools::UUID.parse_hexdigest(value)
    when :string
      UUIDTools::UUID.parse(value)
    end
    raise ArgumentError unless uuid.valid?

    uuid.to_s
  rescue ArgumentError, TypeError
    raise ActiveRecord::SerializationTypeMismatch,
      "Attribute was supposed to be a valid uuid, but was #{value}"
  end
end