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
|
# File 'lib/daily/has_data.rb', line 13
def has_data field
attribute = "#{field}_data"
method = "#{field}_json"
valid = "#{field}_json_check"
serialize attribute, Hash
define_method method do
val = instance_variable_get("@#{method}")
return val if val
data = send(attribute)
return nil if data.blank?
JSON.pretty_generate(data)
end
define_method "#{method}=" do |val|
instance_variable_set("@#{method}", val)
send("#{attribute}=", nil)
return if val.blank?
begin
send("#{attribute}=", JSON.parse(val))
rescue
end
end
define_method valid do
val = instance_variable_get("@#{method}")
return if val.blank?
begin
JSON.parse(val)
rescue => ex
self.errors.add(method.to_sym, ex.message)
end
end
validate valid
end
|