Skip to Content Skip to Search

ActiveRecord::Encryption uses encryption contexts to configure the different entities used to encrypt/decrypt at a given moment in time.

By default, the library uses a default encryption context. This is the Context that gets configured initially via config.active_record.encryption options. Library users can define nested encryption contexts when running blocks of code.

See Context.

Methods
C
P
W

Instance Public methods

context()

Returns the current context. By default it will return the current context.

# File activerecord/lib/active_record/encryption/contexts.rb, line 62
def context
  self.current_custom_context || self.default_context
end

current_custom_context()

# File activerecord/lib/active_record/encryption/contexts.rb, line 66
def current_custom_context
  self.custom_contexts&.last
end

protecting_encrypted_data(&block)

Runs the provided block in an encryption context where:

  • Reading encrypted content will return its ciphertext.

  • Writing encrypted content will fail.

# File activerecord/lib/active_record/encryption/contexts.rb, line 57
def protecting_encrypted_data(&block)
  with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block
end

with_encryption_context(properties)

Configures a custom encryption context to use when running the provided block of code.

It supports overriding all the properties defined in Context.

Example:

ActiveRecord::Encryption.with_encryption_context(encryptor: ActiveRecord::Encryption::NullEncryptor.new) do
  ...
end

Encryption contexts can be nested.

# File activerecord/lib/active_record/encryption/contexts.rb, line 33
def with_encryption_context(properties)
  self.custom_contexts ||= []
  self.custom_contexts << default_context.dup
  properties.each do |key, value|
    self.current_custom_context.send("#{key}=", value)
  end

  yield
ensure
  self.custom_contexts.pop
end

without_encryption(&block)

Runs the provided block in an encryption context where encryption is disabled:

  • Reading encrypted content will return its ciphertexts.

  • Writing encrypted content will write its clear text.

# File activerecord/lib/active_record/encryption/contexts.rb, line 49
def without_encryption(&block)
  with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block
end