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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/document_record.rb', line 16
def document_field name
raise "Field must exist in record in order to become a document field" unless column_names.include? name.to_s
@@_document_field_name = name
@@_index_fields ||= []
class_eval do
alias_method :regular_assign_attributes, :assign_attributes
alias_method :regular_method_missing, :method_missing
alias_method :regular_save, :save
def read_serialized_hash_attribute field_name
raw = read_attribute field_name
raw && Serializer.load( raw ) || {}
end
def write_serialized_hash_attribute field_name, hash
write_attribute field_name, Serializer.dump(hash)
end
def document
@document ||= ::DocumentHash::Core[read_serialized_hash_attribute(@@_document_field_name)].tap do |d|
d.before_change do |path, value|
key = path.join "_"
value = case self.class.columns_hash[key].type
when :integer then value.to_i
else value
end if self.class.columns_hash[key]
value
end
d.after_change do |path, value|
key = path.join "_"
write_attribute key, value if self.class.columns_hash[key]
end
end
end
def save *arguments
save_document
regular_save *arguments
end
def save! *arguments
save(*arguments) || raise(RecordNotSaved)
end
def touch!
document.touch!
save
end
def save_document
write_serialized_hash_attribute @@_document_field_name, document.to_hash
end
def assign_attributes new_attributes, options
new_attributes.each do | key, value |
self.send "#{key}=".to_sym, value
end
end
def method_missing method, *args
if method =~ /(.*)=$/
document[$1] = args.shift
else
document[method.to_s]
end
end
def is_indexed? attr
self.class.column_names.include? attr.to_s
end
def as_json options = {}
( read_serialized_hash_attribute(@@_document_field_name) || {} ).merge(super.reject{ |k, v| k === @@_document_field_name.to_s })
end
end
column_names.each do |column|
class_eval " def \#{column}\n document[\"\#{column}\"] || read_attribute(\"\#{column}\")\n end\n def \#{column}= value\n document[\"\#{column}\"] = value\n end\n METHOD\n end\nend\n"
|