Coder Social home page Coder Social logo

crowdint / acts_as_shopping_cart Goto Github PK

View Code? Open in Web Editor NEW
258.0 68.0 88.0 402 KB

Simple Shopping Cart implementation, Official repo: https://github.com/dabit/acts_as_shopping_cart

License: MIT License

Ruby 87.53% Shell 0.97% Groff 1.03% Gherkin 10.46%

acts_as_shopping_cart's Introduction

acts_as_shopping_cart

A simple shopping cart implementation.

Build Status Code Climate Test Coverage

You can find an example application here.

Install

Rails 3

As of Version 0.2.0 Rails 3 is no longer supported. Please use the 0-1-x branch if you still need to implement this gem in a Rails 3 app

Include it in your Gemfile

gem 'acts_as_shopping_cart', :github => 'crowdint/acts_as_shopping_cart', :branch => '0-1-x'

And run bundler

bundle install

Rails 4

Just include it in your Gemfile as:

gem 'acts_as_shopping_cart', '~> 0.2.1'

And run bundle install

bundle install

Usage

You need two models, one to hold the Shopping Carts and another to hold the Items

You can use any name for the models, you just have to let each model know about each other.

Examples

For the Shopping Cart:

class Cart < ActiveRecord::Base
  acts_as_shopping_cart_using :cart_item
end

For the items:

class CartItem < ActiveRecord::Base
  acts_as_shopping_cart_item_for :cart
end

or, if you want to use convention over configuration, make sure your models are called ShoppingCart and ShoppingCartItem, then just use the shortcuts:

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart
end

class ShoppingCartItem < ActiveRecord::Base
  acts_as_shopping_cart_item
end

Migrations

In order for this to work, the Shopping Cart Item model should have the following fields:

create_table :cart_items do |t|
  t.shopping_cart_item_fields # Creates the cart items fields
end

Shopping Cart Items

Your ShoppingCart class will have a shopping_cart_items association that returns all the ShoppingCartItem objects in your cart.

Add Items

To add an item to the cart you use the add method. You have to send the object and the price of the object as parameters.

So, if you had a Product class, you would do something like this:

@cart = Cart.create
@product = Product.find(1)

@cart.add(@product, 99.99)

In the case where your product has a price field you could do something like:

@cart.add(@product, @product.price)

I tried to make it independent to the models in case you calculate discounts, sale prices or anything customized.

You can include a quantity parameter too.

@cart.add(@product, 99.99, 5)

In that case, you would add 5 of the same products to the shopping cart. If you don't specify the quantity 1 will be assumed.

Remove Items

To remove an item from the cart you can use the remove method. You just have to send the object and the quantity you want to remove.

@cart.remove(@product, 1)

Empty the cart

To remove all the items in the cart at once, just use the clear method

@cart.clear

Total

You can find out about the total using the total method:

@cart.total # => 99.99

Taxes

Taxes by default are calculated by multiplying subtotal times 8.25

If you want to change the way taxes are calculated, override the taxes method on your class that acts_as_shopping_cart.

Example:

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart

  def taxes
    (subtotal - 10) * 8.3
  end
end

If you just want to update the percentage, just override the tax_pct method.

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart

  def tax_pct
    3.5
  end
end

Shipping Cost

Shipping cost will be added to the total. By default its calculated as 0, but you can just override the shipping_cost method on your cart class depending on your needs.

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart

  def shipping_cost
    5 # defines a flat $5 rate
  end
end

Total unique items

You can find out how many unique items you have on your cart using the total_unique_items method.

So, if you had something like:

@cart.add(@product, 99.99, 5)

Then,

@cart.total_unique_items # => 5

Development

Install the dependencies

bundle install

Test

Run rspec

rspec spec

Run cucumber features

cucumber

Both:

rake

About the author

Crowd Interactive is a leading Ruby and Rails consultancy firm based in Mexico currently doing business with startups in the United States. We specialize in building and growing Rails applications, by increasing your IT crew onsite or offsite. We pick our projects carefully, as we only work with companies we believe in.

acts_as_shopping_cart's People

Contributors

abatko avatar chischaschos avatar choonkeat avatar dabit avatar marcusvmsa avatar strukturedkaos avatar ulrichthomasgabor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

acts_as_shopping_cart's Issues

Its now working with STI as item_for search for Parent class

def item_for(object)
  shopping_cart_items.where(:item => object).first
end

This returns parent object and if child object is passed as object it returns nil which makes remove call not to execute.

To work with STI

I have to override this method in my model which act like Shopping Cart.

  • We should rollback #13.

undefined method `*' for nil:NilClass

I'm getting this exception using the show.html.erb in the demo application. You can view my current application in my bootstrapped_devise repo.
Thanks,

Antarr

undefined method `*' for nil:NilClass
Extracted source (around line #5):

2:
3: <%= render :partial => 'shopping_cart_item', :collection => @shopping_cart.shopping_cart_items %>
4:
5:

SubTotal:<%= number_to_currency @shopping_cart.subtotal %>

6:
Taxes:<%= number_to_currency @shopping_cart.taxes %>

7:
Total:<%= number_to_currency @shopping_cart.total %>

How to retrieve items from a cart?

I have added several products in the cart. But I want to get the list of all added products back during a confirmation stage. Kindly help me to get array of all the added products in the cart

cannot set currency

Hi,
I'm using the GEM on a rails 5 project.
Everything is working perfectly but i cannot change the currency to eur.

i have in my MoneyRails initializer
config.default_currency = :eur

but still does not work.

Thanks !

Francis

undefined local variable or method `acts_as_shopping_cart' - Rails 4

I am using Rails 4 and I got this error:

undefined local variable or method `acts_as_shopping_cart' for #Class:0x0000000766b320

app/models/shopping_cart.rb:
class ShoppingCart < ActiveRecord::Base
acts_as_shopping_cart
end

Anyone could help me, I couldn't find any information about this error. :(

Uninitialized Constant Error in Controller - Rails 4.1.2

I have got the following in my controller ... following the code from the sample app. I get the error uninitialized constant ShoppingCart::ShoppingCartItem in the create method's second line.

class ShoppingCartsController < ApplicationController
  before_action :extract_shopping_cart

  def create
    @product = Product.find(params[:product_id])
    @shopping_cart.add(@product, @product.price)
    redirect_to shopping_cart_path
  end

  def show

  end

  private
  def extract_shopping_cart
    shopping_cart_id = session[:shopping_cart_id]
    @shopping_cart = session[:shopping_cart_id] ? ShoppingCart.find(shopping_cart_id) : ShoppingCart.create
    session[:shopping_cart_id] = @shopping_cart.id
  end
end

Return the object added to cart

In some cases in useful get the last object added to Cart.

For example

item = @shopping_cart.add(obj)

Add the code to support previous is quite easy. Maybe you should ask why return the last object? I was working on an app where I need get this object due to the UI expected another action with this one.

Gem Update

Thanks for this great gem. I want to use it on my project but it seems that the latest gem version does not include the non-cumulative cart.add method.

So will you please update the gem?

Can't mass-assign protected attributes: item

I'm using this plugin with the convetions, but get this error:

ERROR:

Can't mass-assign protected attributes: item

class ShoppingCartsController < ApplicationController
before_filter :extract_shopping_cart
def create
@Product = Video.find(params[:product_id])
@shopping_cart.add(@Product, @product.price)
redirect_to shopping_cart_path
end
def show

cart total and quantity not updating

when I do cart.add product, product.price, 1 ,the product is added to cart, but when this is repeated, ie to add one more quantity for same product, the quantity isn't updated in the cart but I can see an update query on cart_items. This is strange.

Sample Migration File

Here's a sample migration new users can run to get the database working. Just including this here to save someone else some time...

class AddShoppingCartSchema < ActiveRecord::Migration
  def change
    create_table :carts do |t|

    end
    create_table :cart_items do |t|
      t.shopping_cart_item_fields # Creates the cart items fields
    end
  end
end

How can i stub a cart?

Hello,

in the process of implementing a rspec test for my controller, i need to stub a shopping cart, so that my "method" doesn't fail because of an empty cart. Is that possible? I've been trying to do something like

  allow_any_instance_of(CartItem).to receive(quantity: 1, item_type: "FrameItem", price: 60)

but this give me errors like " CartItem does not implement #quantity". Surely i am doing something wrong. Appreciate the help!!

How do I implement quantity editing?

Using the models recommended by the guide, and even the example application, I have the following in my shopping_cart_item.html.erb.

<td><%= shopping_cart_item.item.name %></td>
<td><%= shopping_cart_item.item.price %></td>
<td><%= shopping_cart_item.quantity %></td>

But I want to allow users to change the quantity - from say a drop-down menu (so a select tag from a collection).

But I am not quite sure how to approach that.

I would also like to add other attributes to my item - like a size of an item, color, etc.

I would like my store owner to be able to specify those things (i.e. size, color, etc.).

How do I do that?

Thanks.

Could not find gem after bundle install

gem 'acts_as_shopping_cart', '~> 0.2.1'

$ bundle install
$ rails s
...
Could not find acts_as_shopping_cart-0.2.1 in any of the sources
Run `bundle install` to install missing gems.

what's the problem?

Price as Money?

Why not use the money gem or similar so that currency can be handled correctly in the cart?

Multiple shipping costs

I would like to have multiple shipping costs for certain states.

acts_as_shopping_cart only allows one definition of shipping rate.

Does acts_as_shopping_cart have definition for multiple shipping rates?

Add multiple product types to cart.

I have two product pages which i would like to add in the cart. Example i have 'Product1' and 'Product2'

The only clue from https://github.com/crowdint/acts_as_shopping_cart_app is that the item is added to the cart is with

def create
  @product = Product.find(params[:product_id])
  @shopping_cart.add(@product, @product.price)
  redirect_to shopping_cart_path
end

from https://github.com/crowdint/acts_as_shopping_cart_app/blob/master/app/controllers/shopping_carts_controller.rb

Is it possible?

No route matches

Got this error to my function add_item

{:action=>"add_item", :id=>nil, :controller=>"comprar"}

Someone already get this message?

Thanks!

Due to monkey patching `empty?` validates presence no longer works.

class Redemption < ActiveRecord::Base
  belongs_to :shopping_cart

  validates :shopping_cart, presence: true
end

cart = ShoppingCart.create(...)
redemption = Redemption.new(shopping_cart: cart)
redemption.valid?
redemption.errors # => #<ActiveModel::Errors:... @base=#<Redemption id: nil, shopping_cart_id: ..., created_at: nil, updated_at: nil>, @messages={:shopping_cart=>["can't be blank"]}>

This was pretty annoying to run into :/

CartItem price as decimal?

Is there a reason I shouldn't convert the CartItem price to decimal?

My products and orders have prices in decimals and converting them from and to float makes me a bit queasy...

Thanks!

How can I set currency?

shopping_cart_item_fields creates column price_currency with default value "USD" in shopping_cart_items
How can I set other currency?

Rails 5 Support?

Hello, I have been using this game for a while. I would like to say thanks. It has served me well. But soon I will be updating my application to rails 5. I wanted to know if there was going to be an update so this gem can work in rails 5.

Thank you

"remove" with different item_types

If I'm reading the source code right, the "remove" method will remove based on item_id. But how to remove by item_id and item_type (in case one can add item from different models / types)?

See my sample DB content

screen shot 2014-09-01 at 16 44 40

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.