Class: Motion::Serializer

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

Constant Summary collapse

NULL_BYTE =
"\0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret: Motion.config.secret, revision: Motion.config.revision) ⇒ Serializer

Returns a new instance of Serializer.

Raises:



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/motion/serializer.rb', line 22

def initialize(
  secret: Motion.config.secret,
  revision: Motion.config.revision
)
  unless secret.each_byte.count >= self.class.minimum_secret_byte_length
    raise BadSecretError.new(self.class.minimum_secret_byte_length)
  end

  raise BadRevisionError if revision.include?(NULL_BYTE)

  @secret = secret
  @revision = revision
end

Instance Attribute Details

#revisionObject (readonly)

Returns the value of attribute revision.



16
17
18
# File 'lib/motion/serializer.rb', line 16

def revision
  @revision
end

#secretObject (readonly)

Returns the value of attribute secret.



16
17
18
# File 'lib/motion/serializer.rb', line 16

def secret
  @secret
end

Class Method Details

.minimum_secret_byte_lengthObject



18
19
20
# File 'lib/motion/serializer.rb', line 18

def self.minimum_secret_byte_length
  ActiveSupport::MessageEncryptor.key_len
end

Instance Method Details

#deserialize(serialized_component) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/motion/serializer.rb', line 50

def deserialize(serialized_component)
  state_with_revision = decrypt_and_verify(serialized_component)
  serialized_revision, state = state_with_revision.split(NULL_BYTE, 2)
  component = load(inflate(state))

  if revision == serialized_revision
    component
  else
    component.class.upgrade_from(serialized_revision, component)
  end
end

#serialize(component) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/motion/serializer.rb', line 40

def serialize(component)
  state = deflate(dump(component))
  state_with_revision = "#{revision}#{NULL_BYTE}#{state}"

  [
    salted_digest(state_with_revision),
    encrypt_and_sign(state_with_revision)
  ]
end

#weak_digest(component) ⇒ Object



36
37
38
# File 'lib/motion/serializer.rb', line 36

def weak_digest(component)
  dump(component).hash
end