Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Commit

Permalink
raise an exception when replacing frozen association
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanb committed Jul 14, 2008
1 parent c340141 commit c405d2c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Original file line Diff line number Diff line change
@@ -1,3 +1,5 @@
* raise an exception when trying to replace frozen association

*0.1.0* (July 14th, 2008) *0.1.0* (July 14th, 2008)


* initial release * initial release
10 changes: 5 additions & 5 deletions lib/association_freezer/belongs_to_freezer.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@ def fetch(*args)
frozen || nonfrozen(*args) frozen || nonfrozen(*args)
end end


def frozen?
frozen_data
end

private private


def frozen def frozen
@frozen ||= load_frozen if frozen_data @frozen ||= load_frozen if frozen?
end end


def load_frozen def load_frozen
Expand All @@ -40,10 +44,6 @@ def frozen_data
@owner.read_attribute("frozen_#{name}") @owner.read_attribute("frozen_#{name}")
end end


def attribute_name
"frozen_#{name}"
end

def target_class def target_class
@reflection.klass @reflection.klass
end end
Expand Down
10 changes: 10 additions & 0 deletions lib/association_freezer/method_generator.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ def generate
send(freezer).fetch(*args) send(freezer).fetch(*args)
end end
model_class.alias_method_chain reflection.name, :frozen_check model_class.alias_method_chain reflection.name, :frozen_check

generate_method "#{reflection.name}_with_frozen_check=" do |*args|
if send(freezer).frozen?
# TODO make this a custom exception
raise "Unable to set #{reflection.name} because association is frozen."
else
send("#{reflection.name}_without_frozen_check=", *args)
end
end
model_class.alias_method_chain "#{reflection.name}=", :frozen_check
end end


private private
Expand Down
9 changes: 9 additions & 0 deletions spec/freezer_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@
@order.unfreeze_ship_method @order.unfreeze_ship_method
@order.ship_method.price.should == 8 @order.ship_method.price.should == 8
end end

it "should raise an exception when attempting to save associated model" do
lambda { @order.ship_method.save }.should raise_error(Exception)
lambda { @order.ship_method.save! }.should raise_error(Exception)
end

it "should raise an exception when attempting to replace association" do
lambda { @order.ship_method = ShipMethod.new }.should raise_error(Exception)
end
end end
end end
end end

0 comments on commit c405d2c

Please sign in to comment.