Skip to content

Instantly share code, notes, and snippets.

@jeffutter
Created November 7, 2012 06:20
Show Gist options
  • Save jeffutter/638e269830a5d99c4361 to your computer and use it in GitHub Desktop.
Save jeffutter/638e269830a5d99c4361 to your computer and use it in GitHub Desktop.
order
class Order
include ActiveModel::Validations
attr_accessor :shipping_address, :billing_address, :items, :packages
def initialize(attributes = {})
attributes.each do |name, value|
if ['shipping_address', 'billing_address'].include? name and value.is_a? Hash
value = Address.new(value)
end
send("#{name}=", value)
end
self.shipping_address ||= Address.new
self.billing_address ||= Address.new
self.items ||= Array.new
end
def persisted?
false
end
def get_items
GalleryItem.in(:id => self.items.keys).map{|x| {
:name => x.name,
:quantity => self.items[x.id.to_s],
:description => x.details,
:amount => ("%.2f" % ( x.price * 100 )).to_i
}}
end
def compute_packages
self.packages = Array.new
items = get_items
items.each do |item|
packageval = self.packages.find(){|x| x.add_item(item)}
unless packageval
p = Package.new
p.add_item(item)
self.packages.push(p)
end
end
end
def calculate_shipping
origin = Location.new(:country => 'US',
:state => 'NY',
:city => 'Canton',
:zip => '13617')
destination = Location.new(:country => self.shipping_address.country,
:state => self.shipping_address.state,
:city => self.shipping_address.city,
:zip => self.shipping_address.zip)
usps = USPS.new(:login => '432JUDIT6085')
response = usps.find_rates(origin, destination, packages)
usps_rates = response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}
end
end
class Package
attr_accessor :spaces, :items, :weight
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
self.spaces ||= 6
self.weight ||= 0
self.items ||= Array.new
end
def persisted?
false
end
def add_item(item)
if item.gallery.slug == 'scarves'
spaces = 3
weight = 1
else
spaces = 1
weight = 0.33
end
if spaces <= self.spaces
self.items.push item
self.weight += weight
return true
else
return false
end
end
end
class Address
include ActiveModel::Validations
attr_accessor :first_name, :middle_intial, :last_name, :country, :address1, :address2, :city, :state, :zip, :phone
validates_presence_of :first_name, :last_name, :country, :address1, :city, :state, :zip, :phone
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment