Skip to content

Instantly share code, notes, and snippets.

@aloucas
Last active October 31, 2021 15:16
Show Gist options
  • Select an option

  • Save aloucas/b874d9f1adc8050a1497c00c1429c76f to your computer and use it in GitHub Desktop.

Select an option

Save aloucas/b874d9f1adc8050a1497c00c1429c76f to your computer and use it in GitHub Desktop.

Revisions

  1. aloucas revised this gist Sep 20, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion encryptor.rb
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,7 @@ def has_encrypted_attributes(*attrs)
    attrs.each do |attr|
    # Define the dynamic getter
    define_method(attr) do
    Encryptor.crypt.decrypt_and_verify(self[attr])
    self[attr].present? ? Encryptor.crypt.decrypt_and_verify(self[attr]) : self[attr]
    end
    # Define the dynamic setter
    define_method("#{attr.to_s}=") do |val|
  2. aloucas created this gist Sep 14, 2017.
    23 changes: 23 additions & 0 deletions encryptor.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    # 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
    Encryptor.crypt.decrypt_and_verify(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
    10 changes: 10 additions & 0 deletions model_with_encrypted_atts.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    # app/models/model_with_encrypted_atts.rb
    class ModelWithEncryptedAttrs < ApplicationRecord
    # Modules
    extend Encryptor

    # Abilities
    has_encrypted_attributes :attribute_1,
    :attribute_2

    end