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 <<-RUBY, __FILE__, __LINE__ + 1
def #{field_cache}
if defined?(@#{property})
@#{property}
else
# define @#{property} to avoid mutual recursion
@#{property} = nil
@#{property} = #{property}
end
end
def #{field_cache}=(new_value)
@#{property} = new_value
end
RUBY
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{property}
# Return cached
return #{field_cache} if defined?(@#{property}) && #{field_cache}
# No assignment yet, save property if not already saved
self.#{field_orig}= self[:#{property}] if !#{field_orig}
# Set cached from pre
value = cerealize_decode(:#{property}, #{field_orig})
raise ActiveRecord::SerializationTypeMismatch, "expected #{klass}, got \#{value.class}" \\
if #{klass.inspect} && !value.nil? && !value.kind_of?(#{klass})
self.#{field_cache} = value
end
RUBY
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{property}=(value)
#{property}_will_change! if #{field_cache} != value
self.#{field_cache} = value
end
RUBY
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{property}_update_if_dirty
# See if we have a new cur value
if instance_variable_defined?('@#{property}')
value = #{field_cache}
value_enc = cerealize_encode(:#{property}, value)
# See if no orig at all (i.e. it was written to before
# being read), or if different. When comparing, compare
# both marshalized string, and Object ==.
#
if !#{field_orig} ||
(value_enc != #{field_orig} &&
value != cerealize_decode(:#{property}, #{field_orig}))
self[:#{property}] = value_enc
end
remove_instance_variable('@#{property}')
end
self.#{field_orig} = nil
end
RUBY
include mod unless self < mod
before_save("#{property}_update_if_dirty")
end
|