class Shopicruit

Constants

VERSION

Public Class Methods

leastCost(maxWeight, return_type, item_list) click to toggle source
# File lib/shopicruit.rb, line 13
def self.leastCost(maxWeight, return_type, item_list)
        products      = get_product_list(item_list).sort_by{ |key, value| value["price"] / value["weight"] }.to_h
        result                = calculate(products, maxWeight)
        return result[return_type]
end
maxAmount(maxWeight, return_type, item_list) click to toggle source
# File lib/shopicruit.rb, line 6
def self.maxAmount(maxWeight, return_type, item_list)
        products      = get_product_list(item_list).sort_by{ |key, value| value["weight"] }.to_h
        result                = calculate(products, maxWeight)
        return result[return_type]
end

Private Class Methods

calculate(products, maxWeight) click to toggle source
# File lib/shopicruit.rb, line 39
def self.calculate(products, maxWeight)
        totalWeight = 0.0
        totalPrice    = 0.0
        cart          = []

        products.each do |product_name, product_info|
                if (totalWeight + product_info["weight"] <= maxWeight)
                        totalWeight += product_info["weight"]
                        totalPrice  += product_info["price"]
                        cart.push product_name
                end
        end
        return {"cost" => ("$" + '%.2f' % totalPrice), "weight" => ('%.2f' % totalWeight + "kg"), "products" => cart}
end
get_product_list(item_list) click to toggle source
# File lib/shopicruit.rb, line 20
def self.get_product_list(item_list)
        uri = URI("http://shopicruit.myshopify.com/products.json")

        res = Net::HTTP.get(uri)
        product_list = JSON.parse(res)

        desiredProductList = {}
        product_list["products"].each do |item|
                if (item_list.include? item["product_type"])
                        item["variants"].each do |var|
                                title = item["title"] + " (" + var["title"] + ")"
                                desiredProductList[title] = { "weight" => var["grams"]/1000.0, "price" => var["price"].to_f }
                        end
                end
        end
        return desiredProductList
end