Class: Chamber::Types::Secured

Inherits:
CHAMBER_TYPE_VALUE_SUPERCLASS
  • Object
show all
Defined in:
lib/chamber/types/secured.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(decryption_keys: ::Chamber.configuration.decryption_keys, encryption_keys: ::Chamber.configuration.encryption_keys) ⇒ Secured

Returns a new instance of Secured.



26
27
28
29
30
31
32
# File 'lib/chamber/types/secured.rb', line 26

def initialize(decryption_keys: ::Chamber.configuration.decryption_keys,
               encryption_keys: ::Chamber.configuration.encryption_keys)
  self.decryption_keys = decryption_keys
  self.encryption_keys = encryption_keys

  super()
end

Instance Attribute Details

#decryption_keysObject

Returns the value of attribute decryption_keys.



23
24
25
# File 'lib/chamber/types/secured.rb', line 23

def decryption_keys
  @decryption_keys
end

#encryption_keysObject

Returns the value of attribute encryption_keys.



23
24
25
# File 'lib/chamber/types/secured.rb', line 23

def encryption_keys
  @encryption_keys
end

Instance Method Details

#cast(value) ⇒ Object Also known as: type_cast_from_user



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/chamber/types/secured.rb', line 38

def cast(value)
  case value
  when Hash
    value
  when String
    ::JSON.parse(value)
  when NilClass
    nil
  else
    fail ArgumentError, 'Any attributes encrypted with Chamber must be either a Hash or a valid JSON string'
  end
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
# File 'lib/chamber/types/secured.rb', line 74

def changed_in_place?(raw_old_value, new_value)
  deserialize(raw_old_value) == new_value
end

#deserialize(value) ⇒ Object Also known as: type_cast_from_database



52
53
54
55
56
57
58
59
60
# File 'lib/chamber/types/secured.rb', line 52

def deserialize(value)
  value = cast(value)

  return if value.nil?

  Chamber.decrypt(value,
                  decryption_keys: decryption_keys,
                  encryption_keys: encryption_keys)
end

#serialize(value) ⇒ Object Also known as: type_cast_for_database



63
64
65
66
67
68
69
70
71
# File 'lib/chamber/types/secured.rb', line 63

def serialize(value)
  fail ArgumentError, 'Any attributes encrypted with Chamber must be a Hash' unless value.is_a?(Hash)

  ::JSON.dump(
    ::Chamber.encrypt(value,
                      decryption_keys: decryption_keys,
                      encryption_keys: encryption_keys),
  )
end

#typeObject



34
35
36
# File 'lib/chamber/types/secured.rb', line 34

def type
  :jsonb
end