Skip to content

Instantly share code, notes, and snippets.

@olegsobchuk
Created September 2, 2016 11:48
Show Gist options
  • Save olegsobchuk/c8b2590f96262f3dfbc5b9f9e6cd52ee to your computer and use it in GitHub Desktop.
Save olegsobchuk/c8b2590f96262f3dfbc5b9f9e6cd52ee to your computer and use it in GitHub Desktop.
Encrypt Column in Rails
# somewhere in lib or services
module Encryptable
def encrypt_columns(*columns)
columns.each do |column|
if self.column_names.include?("encrypted_#{column}")
self.send(:attr_accessor, column)
define_method "#{column}=" do |value|
self["encrypted_#{column}"] = self.class.verifier.generate(value)
end
define_method "#{column}" do
self["encrypted_#{column}"].nil? ? nil : self.class.verifier.verify(self["encrypted_#{column}"])
end
end
end
end
def verifier
@verifier ||= ActiveSupport::MessageVerifier.new(SECRETS[:encrypt_key])
end
end
# in DB you need create columns with name
# encrypted_password, encrypted_secret_key # encrypted_#{column_name}
# than in model
class MyModel < ApplicationRecord
encrypt_columns :password, :secret_key
....
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment