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
|
# File 'lib/serialize_virtual_attributes.rb', line 10
def serialize_virtual_attrs(*attrs, opts)
if attrs.nil? or (attrs.compact! and attrs.empty?)
raise ArgumentError.new("No virtual attributes provided")
end
to = HashWithIndifferentAccess.new(opts).fetch(:to) rescue nil
if to.blank?
raise ArgumentError.new("No serialized column provided")
end
if self.column_names.index(to.to_s).nil?
raise ArgumentError.new("`#{to}` is not a valid column of table `#{self.table_name}`")
end
attrs.each do |attr|
if self.column_names.index(attr.to_s).present?
raise ArgumentError.new("`#{attr}` is not supposed to be a virtual attribute")
end
if !self.accessible_attributes.include?(attr)
self.accessible_attributes << attr
end
define_method "#{attr}=" do |val|
self.public_send(to).send('[]=', attr, val)
end
define_method attr do
self.public_send(to).send('[]', attr)
end
end
end
|