Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Provides a convenient DSL for organizing a price breakdown in a class.
Ruby
tree: eebec48b64

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
rails
test
.gitignore
LICENSE
README.md
Rakefile
VERSION
has_price.gemspec

README.md

has_price

Let's just say, it organizes your price breakdowns and allows for easy retrieval of price subgroups and subtotals, as well as simple serialization for your receipts.

Install

Make sure gemcutter.org is in your sources.

  sudo gem install has_price

In rails environment:

  config.gem "has_price"

For any generic Ruby class:

  require 'has_price'
  include HasPrice::HasPrice

P.S. Usage as Rails plugin is supported too, but gem is preferred.

Organize

Say you have a Product class with some attributes which price depends on. For this example assume that base_price, federal_tax, and state_tax are integer attributes existing on Product model.

  class Product < ActiveRecord::Base
    has_many :discounts
  end

has_price provides a small DSL with two methods, item and group, to help you organize this.

  class Product < ActiveRecord::Base
    has_many :discounts
    
    has_price do
      item base_price, "base"
      group "taxes" do
        item federal_tax, "federal"
        item state_tax, "state"
      end
      group "discounts" do
        discounts.each do |discount|
          item discount.amount, discount.title
        end
      end
    end
  end

What we've done just now is — built instance method price on products. Now you can use it as so.

  # Hypothetically all these numbers are coming from the above declared instance methods.
  
  product = Product.find(1)
  product.price               # => Price object
  product.price.total         # => 500
  product.price.base          # => 400
  product.price.taxes         # => Price object
  product.price.taxes.federal # => 50
  product.price.taxes.total   # => 100
  product.discounts.total     # => -50

Serialize

Price object actually inherits from a plain old Hash. Therefore, this will work:

  class Receipt < ActiveRecord::Base
    serialize :price, Hash
  end

Now passing the whole price breakdown into receipt is as simple as receipt.price = product.price.

Something went wrong with that request. Please try again.