-
Notifications
You must be signed in to change notification settings - Fork 0
/
acts_as_maskable_attribute.rb
52 lines (41 loc) · 1.59 KB
/
acts_as_maskable_attribute.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
module MaskableAttribute
module ActsAsMaskableAttribute
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
##
# Specifies an attribute to be masked, followed by masks to be made available to the attribute.
#
# ==== Examples
#
# class Foo < ActiveRecord::Base
# maskable_attrribute :some_attribute,
# [ :some_method_be_used_as_a_mask, :another_attribute_mask ]
# end
def maskable_attribute(attribute_to_mask, masks, options = {})
raise ArgumentError, "invalid argument (expected attribute)" unless column_names.include? attribute_to_mask.to_s
cattr_accessor :masks
self.masks ||= {}
self.masks[attribute_to_mask] = masks
self.masks
define_method attribute_to_mask do
send("maskable_#{attribute_to_mask}").to_s
#masked_attribute attribute_to_mask, options
end
define_method "#{attribute_to_mask}=" do |value|
#write_attribute attribute_to_mask, masked_attribute(attribute_to_mask, options).set(value)
send :write_attribute, attribute_to_mask, value
end
define_method "maskable_#{attribute_to_mask}" do
masked_attribute attribute_to_mask, options
end
end
end
attr_accessor :masked_attribute
def masked_attribute(attribute, options)
@masked_attribute ||= MaskableAttribute.new self, attribute, self.class.masks[attribute], options
end
end
end
ActiveRecord::Base.send :include, MaskableAttribute::ActsAsMaskableAttribute