Permalink
Browse files

refactoring out belongs_to freezer class

  • Loading branch information...
1 parent 9951c53 commit be01afc49fce2d7a96b967be786eea3c712c9c91 @ryanb committed Jul 14, 2008
@@ -1,3 +1,4 @@
$:.unshift(File.dirname(__FILE__))
require 'association_freezer/model_additions'
require 'association_freezer/method_generator'
+require 'association_freezer/belongs_to_freezer'
@@ -0,0 +1,47 @@
+module AssociationFreezer
+ class BelongsToFreezer
+ def initialize(owner, reflection)
+ @owner = owner
+ @reflection = reflection
+ end
+
+ def freeze
+ @owner.send(name, true).freeze
+ freeze_to_db(Marshal.dump(@owner.send(name).attributes))
+ end
+
+ def unfreeze
+ # TODO
+ end
+
+ def frozen(force_reload = false)
+ if @frozen && !force_reload
+ @frozen
+ elsif frozen_in_db
+ @frozen = target_class.new(Marshal.load(frozen_in_db).except('id')).freeze
+ end
+ end
+
+ private
+
+ def freeze_to_db(data)
+ @owner.write_attribute("frozen_#{name}", data)
+ end
+
+ def frozen_in_db
+ @owner.read_attribute("frozen_#{name}")
+ end
+
+ def attribute_name
+ "frozen_#{name}"
+ end
+
+ def target_class
+ @reflection.klass
+ end
+
+ def name
+ @reflection.name
+ end
+ end
+end
@@ -10,29 +10,29 @@ def generate
# because otherwise it will result in an endless loop the way alias method works.
return if previously_generated? || !frozen_column_exists?
- association = @reflection
-
- generate_method "freeze_#{association.name}" do
- send(association.name, true).freeze
- write_attribute("frozen_#{association.name}", Marshal.dump(send(association.name).attributes))
+ reflection = @reflection
+ freezer = "#{reflection.name}_freezer"
+
+ generate_method freezer do
+ read_attribute("@#{freezer}") || write_attribute("@#{freezer}", BelongsToFreezer.new(self, reflection))
end
-
- generate_method "unfreeze_#{association.name}" do
+
+ generate_method "freeze_#{reflection.name}" do
+ send(freezer).freeze
end
-
- generate_method "#{association.name}_with_frozen_check" do |*args|
- if !instance_variable_defined?("@#{association.name}") || args.first # force reload
- if read_attribute("frozen_#{association.name}")
- association.klass.new(Marshal.load(read_attribute("frozen_#{association.name}")).except('id'))
- else
- send("#{association.name}_without_frozen_check", *args)
- end
- end
- instance_variable_get("@#{association.name}")
+
+ generate_method "unfreeze_#{reflection.name}" do
+ send(freezer).unfreeze
end
- model_class.alias_method_chain association.name, :frozen_check
+
+ generate_method "#{reflection.name}_with_frozen_check" do |*args|
+ send(freezer).frozen(*args) || send("#{reflection.name}_without_frozen_check", *args)
+ end
+ model_class.alias_method_chain reflection.name, :frozen_check
end
+ private
+
def previously_generated?
model_class.instance_methods.include? "freeze_#{@reflection.name}"
end

0 comments on commit be01afc

Please sign in to comment.