我正在使用Ruby Sinatra的购物车(使用Rspec和Capybara进行TDD)并且不明白如何使“购买”按钮将商品添加到购物车。
寻找一些帮助来理解我的问题和重构的建议,因为我确信在这个阶段我犯了很多可怕的错误。
我认为相关部分:
查看:
<% @products.each do |product| %>
<h3><div class="productName">
<%= product["name"] %>
</div></h3>
<% if product["stock"] > 0 %>
<form action="/" method="POST">
<button type="submit" name="item" class="buyButton">Buy</button>
</form>
<% else %>
<button value="Sold out" class="soldOutButton" disabled>Sold out</button>
<% end %>
<% end %>
控制器:
class RubyShop
shop = Shop.new
before do
@products ||= shop.products
@cart ||= shop.cart
end
get "/" do
session[:item] = params["item"]
@cart.add(session[:item])
erb :products
end
post "/" do
session[:item] = params["item"]
@cart.add(session[:item])
erb :products
end
end
型号:
# shop.rb
require "json"
require_relative "cart"
class Shop
attr_reader :products, :cart
def initialize options = { products: "products.json" }
file = File.read options[:products]
@products = JSON.parse file
@cart = Cart.new
end
end
class Cart
attr_reader :products
def initialize
@products = []
end
def add item
return nil unless item
add_quantity_value_to_hash item
cart_contains_item?(item) ? increment_quantity(item) : add_product(item)
end
def add_quantity_value_to_hash item
item["quantity"] ||= 1
end
def cart_contains_item? item
@products.include? item
end
def increment_quantity item
@products.find do |product|
product["quantity"] += 1 if product["name"] == item["name"]
end
end
def add_product item
@products << item
end
def total
@products.inject(0) do |sum, product|
sum + (product["price"] * product["quantity"])
end
end
end
示例JSON fixture:
[ { "name": "Black trainers",
"category": "Footwear",
"image": "http://www.img.com/1.jpg",
"price": 100.00,
"stock": 99 } ]
点击“购买”时出现此错误:
IndexError at /
string not matched
file: cart.rb location: []= line: 15
我的Rspec测试给了我这个错误:
IndexError:
string not matched
我在网上搜索过该错误但未找到解决方案。