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(options = {}) ⇒ Secured

Returns a new instance of Secured.



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

def initialize(options = {})
  self.encryption_keys = options.fetch(:encryption_keys,
                                       Chamber.configuration.encryption_keys)
  self.decryption_keys = options.fetch(:decryption_keys,
                                       Chamber.configuration.decryption_keys)
end

Instance Attribute Details

#decryption_keysObject

Returns the value of attribute decryption_keys.



25
26
27
# File 'lib/chamber/types/secured.rb', line 25

def decryption_keys
  @decryption_keys
end

#encryption_keysObject

Returns the value of attribute encryption_keys.



25
26
27
# File 'lib/chamber/types/secured.rb', line 25

def encryption_keys
  @encryption_keys
end

Instance Method Details

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



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

def cast(value)
  case value
  when Hash
    value
  when String
    ::ActiveSupport::JSON.decode(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)


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

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



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

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



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

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

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

#typeObject



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

def type
  :jsonb
end