Skip to content

Instantly share code, notes, and snippets.

@aloucas
Last active October 31, 2021 15:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aloucas/b874d9f1adc8050a1497c00c1429c76f to your computer and use it in GitHub Desktop.
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.
# 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
# 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