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/autoserialize.rb', line 10
def autoserialize(attribute, format=:json, db_column=nil, default_value={})
format = validate_serialization_format!(format)
db_column ||= :"#{attribute}_#{format}"
class_name = self.name
options_str = ''
if default_value.respond_to?('with_indifferent_access')
options_str += '.with_indifferent_access'
end
default_value = default_value.inspect
define_methods_str = <<END_DEFINE_METHODS_STRING
def save_#{attribute}
self.#{db_column} = #{class_name}.to_#{format}(@#{attribute}) if @#{attribute}
end
before_validation :save_#{attribute}
def #{attribute}
return @#{attribute} if @#{attribute}
@#{attribute} = ( self.#{db_column} ? #{class_name}.from_#{format}(self.#{db_column}) || #{default_value} : #{default_value} )#{options_str}
end
def #{attribute}=(attr)
self.#{db_column} = #{class_name}.to_#{format}(attr)
end
def #{db_column}=(attr_#{format})
self[:#{db_column}] = attr_#{format}
@#{attribute} = nil # Clear the cached #{attribute}
end
END_DEFINE_METHODS_STRING
self.send(:class_eval, define_methods_str)
end
|