Skip to content

Instantly share code, notes, and snippets.

@patmaddox
Created May 13, 2009 20:17
Show Gist options
  • Save patmaddox/111270 to your computer and use it in GitHub Desktop.
Save patmaddox/111270 to your computer and use it in GitHub Desktop.
class Cart < ActiveRecord::Base
has_many :items
alias_method :items_proxy, :items
def add_item(options)
item = items_proxy.build options
if item.valid?
item
else
items_proxy.delete item
false
end
end
def items
@items ||= ReadOnlyProxy.new(items_proxy)
end
end
describe Cart, "add_item" do
it "should add the item to the list when it's valid" do
cart = Cart.new
cart.add_item :quantity => 5
cart.should have(1).items
end
it "should not add the item when it's not valid" do
cart = Cart.new
cart.add_item :quantity => nil
cart.should have(0).items
end
end
describe Cart, "items" do
it "should not allow build or create to be called on it" do
lambda { Cart.new.items.build :quantity => 5 }.should raise_error(NoMethodError)
end
it "should allow typical read methods" do
cart = Cart.new
cart.add_item :quantity => 5
cart.items.first.should_not be_blank
cart.items.map(&:quantity).should == [5]
end
end
class ReadOnlyProxy
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
include Enumerable
def initialize(proxy)
@proxy = proxy
end
def each(&block)
@proxy.each &block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment