88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
|
# File 'lib/cerealize.rb', line 88
def cerealize property, klass=nil, opt={}
opt[:encoding] ||= :marshal
cerealize_option[property] =
opt.merge(:class => klass,
:codec => Cerealize.codec_get(opt[:encoding]))
field_orig = "#{property}_orig"
field_cache = "#{property}_cache"
attr_accessor field_orig
private field_orig, "#{field_orig}="
mod = if const_defined?(Cerealize::InternalName)
const_get(Cerealize::InternalName)
else
const_set(Cerealize::InternalName, Module.new)
end
mod.module_eval " def \#{field_cache}\n if defined?(@\#{property})\n @\#{property}\n else\n # define @\#{property} to avoid mutual recursion\n @\#{property} = nil\n @\#{property} = \#{property}\n end\n end\n\n def \#{field_cache}=(new_value)\n @\#{property} = new_value\n end\n RUBY\n\n # Invariants:\n # - instance_variable_defined?(field_cache) IFF the READER or WRITER has been called\n # - instance_variable_defined?(field_pre) IFF the READER was called BEFORE\n # any WRITER\n\n # READER method\n #\n mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1\n def \#{property}\n # Return cached\n return \#{field_cache} if defined?(@\#{property}) && \#{field_cache}\n\n # No assignment yet, save property if not already saved\n self.\#{field_orig}= self[:\#{property}] if !\#{field_orig}\n\n # Set cached from pre\n value = cerealize_decode(:\#{property}, \#{field_orig})\n\n raise ActiveRecord::SerializationTypeMismatch, \"expected \#{klass}, got \\\#{value.class}\" \\\\\n if \#{klass.inspect} && !value.nil? && !value.kind_of?(\#{klass})\n\n self.\#{field_cache} = value\n end\n RUBY\n\n # WRITER method\n #\n mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1\n def \#{property}=(value)\n \#{property}_will_change! if \#{field_cache} != value\n self.\#{field_cache} = value\n end\n RUBY\n\n # Callback for before_save\n #\n mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1\n def \#{property}_update_if_dirty\n # See if we have a new cur value\n if instance_variable_defined?('@\#{property}')\n value = \#{field_cache}\n value_enc = cerealize_encode(:\#{property}, value)\n\n # See if no orig at all (i.e. it was written to before\n # being read), or if different. When comparing, compare\n # both marshalized string, and Object ==.\n #\n if !\#{field_orig} ||\n (value_enc != \#{field_orig} &&\n value != cerealize_decode(:\#{property}, \#{field_orig}))\n self[:\#{property}] = value_enc\n end\n\n remove_instance_variable('@\#{property}')\n end\n\n self.\#{field_orig} = nil\n end\n RUBY\n\n include mod unless self < mod\n before_save(\"\#{property}_update_if_dirty\")\nend\n", __FILE__, __LINE__ + 1
|