· 9 years ago · Sep 02, 2016, 07:20 PM
1# somewhere in lib or services
2
3module Encryptable
4 def encrypt_columns(*columns)
5 columns.each do |column|
6 if self.column_names.include?("encrypted_#{column}")
7 self.send(:attr_accessor, column)
8
9 define_method "#{column}=" do |value|
10 self["encrypted_#{column}"] = self.class.verifier.generate(value)
11 end
12
13 define_method "#{column}" do
14 self["encrypted_#{column}"].nil? ? nil : self.class.verifier.verify(self["encrypted_#{column}"])
15 end
16 end
17 end
18 end
19
20 def verifier
21 @verifier ||= ActiveSupport::MessageVerifier.new(SECRETS[:encrypt_key])
22 end
23end
24
25# in DB you need create columns with name
26# encrypted_password, encrypted_secret_key # encrypted_#{column_name}
27
28# than in model
29
30class MyModel < ApplicationRecord
31 encrypt_columns :password, :secret_key
32 ....
33end