Module: Unidom::Common::Concerns::SecureColumn::ClassMethods

Defined in:
app/models/unidom/common/concerns/secure_column.rb

Instance Method Summary collapse

Instance Method Details

#secure_column(name, fields: []) ⇒ Object

配置加密列。如: class YourModel < ApplicationRecord

attr_accessor :identity_card_name, :identity_card_address, :passport_name, :passport_address
include Unidom::Common::Concerns::SecureColumn
secure_column :secure_identity_card, fields: [ :identity_card_name, :identity_card_address ]
secure_column :secure_passport,      fields: [ :passport_name, :passport_address ]

end

model = YourModel.create! identity_card_name: ‘张三’, identity_card_address: ‘地址1’,

passport_name: '李四', passport_address: '地址2'

#identity_card_name 和 #identity_card_address 会被加密后保存到 #secure_identity_card 字段中。 #passport_name 和 #passport_address 会被加密后保存到 #secure_passport 字段中。 model_2 = YourModel.find model.id model_2.identity_card_name # 张三 #secure_identity_card 中存储的加密信息会被自动解密,并存储到 #identity_card_name 和 #identity_card_address 中。



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'app/models/unidom/common/concerns/secure_column.rb', line 68

def secure_column(name, fields: [])

  name                = name.to_s
  self.secure_columns = self.secure_columns||{}
  if secure_columns[name].present?
    raise ArgumentError.new("The #{name} column was defined as a secure column already.")
  else
    secure_columns[name] = fields
  end
  fields.each do |field| attr_accessor field.to_sym if columns_hash[field.to_s].blank? end

  instance_eval do
    before_save do do_encrypt_secure_column name        end
    after_find  do do_decrypt_secure_column name.to_sym end
  end

end