Skip to content

Instantly share code, notes, and snippets.

@trobrock
Created July 27, 2020 20:10
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
# frozen_string_literal: true
module EncryptedAttribute
extend ActiveSupport::Concern
class_methods do
def attr_encrypted(attr)
define_method(attr) do
value = instance_variable_get("@#{attr}")
return value if value
instance_variable_set "@#{attr}",
encryptor.decrypt_and_verify(public_send("encrypted_#{attr}".to_sym))
end
define_method("#{attr}=") do |new_value|
value = encryptor.encrypt_and_sign(new_value)
instance_variable_set("@#{attr}", new_value)
public_send("encrypted_#{attr}=", value)
end
end
end
private
def encryptor
@encryptor = ActiveSupport::MessageEncryptor.new(encryptor_key)
end
def encryptor_key
ENV['RAILS_MASTER_KEY'] || File.read(Rails.application.config.credentials.key_path)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment