Last active
October 31, 2021 15:16
-
-
Save aloucas/b874d9f1adc8050a1497c00c1429c76f to your computer and use it in GitHub Desktop.
How to create dynamic attr_accessors (getters/setters) for encrypted attributes in a Ruby on Rails 5 Model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/encryptor.rb | |
# Module to dynamic encrypt attributes per model | |
module Encryptor | |
def has_encrypted_attributes(*attrs) | |
attrs.each do |attr| | |
# Define the dynamic getter | |
define_method(attr) do | |
self[attr].present? ? Encryptor.crypt.decrypt_and_verify(self[attr]) : self[attr] | |
end | |
# Define the dynamic setter | |
define_method("#{attr.to_s}=") do |val| | |
super(Encryptor.crypt.encrypt_and_sign(val)) | |
end | |
end | |
end | |
protected | |
# Create the base MessageEncryptor based on Rails secret_key_base | |
def self.crypt | |
ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/model_with_encrypted_atts.rb | |
class ModelWithEncryptedAttrs < ApplicationRecord | |
# Modules | |
extend Encryptor | |
# Abilities | |
has_encrypted_attributes :attribute_1, | |
:attribute_2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment