Skip to content

Instantly share code, notes, and snippets.

@kuntoaji
Forked from aloucas/encryptor.rb
Created October 19, 2018 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuntoaji/60c210ab6e47e96411be90590d968645 to your computer and use it in GitHub Desktop.
Save kuntoaji/60c210ab6e47e96411be90590d968645 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