Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require_relative "inet2"
cart = Cart.new(ARGV.delete_at(0))
ARGV.each do |a|
@items.each { |i| cart.add_items(i) if a == i.name }
end
cart.read_from_file
cart.save_to_file
class Cart
attr_reader :items
include ItemContainer
def initialize(owner)
@items = Array.new
@owner = owner
end
def save_to_file
File.open("#{@owner}_cart.txt" , "w") do |f|
@items.each{ |i| f.puts i}
end
end
def read_from_file
File.readlines("#{@owner}_cart.txt").each {|i| @items << i.to_real_item}
@items.uniq!
rescue Errno::ENOENT
File.open("#{@owner}_cart.txt" , "w") {}
puts "file #{@owner}_cart.txt created"
end
end
require_relative "string"
require_relative "item_container"
require_relative "cart"
require_relative "item"
require_relative "order"
require_relative "virtual_item"
require_relative "real_item"
@items = []
@items<< RealItem.new( { :price=>109, :weight=>100, :name=> "car"} )
@items<< RealItem.new( { :price=>101, :weight=>100, :name=> "kettle"} )
@items<< RealItem.new( { :weight=>100, :name=> "dishwasher", :price=>100} )
class Item
@@discount = 0.05
def self.discount
if Time.now.month == 3
return @@discount +0.1
else
return @@discount
end
end
def initialize(options={})
@real_price = options[:price]
@name = options[:name]
end
def info
yield(price)
yield(name)
end
attr_reader :real_price, :name
attr_writer :price
def price
(@real_price - @real_price*self.class.discount) + tax if @real_price
end
def to_s
"#{self.name}:#{self.price}:#{self.weight}"
end
private
def tax
type_tax = if self.class == VirtualItem
1
else
2
end
cost_tax = if @real_price>5
@real_price*0.2
else
@real_price*0.1
end
cost_tax +type_tax
end
end
module ItemContainer
module ClassMethods
def min_price
50
end
end
module InstantMethods
def add_items(item)
unless item.price < self.class.min_price
@items.push item
end
end
def remove_item
@items.pop
end
def validate
@items.each{ |i| puts "Item has no price" if i.price.nil? }
end
def delete_invalid_items
@items.delete_if { |i| i.price.nil? }
end
def count_valid_items
@items.count { |i| i.price }
end
end
def self.included(base)
base.extend ClassMethods
base.class_eval do
include InstantMethods
end
end
end
class RealItem < Item
attr_reader :weight
attr_writer :weight
def initialize(options )
@weight = options [:weight]
super
end
def info
yield (weight)
super
end
end
class String
def to_real_item
fields = self.chomp
fields = fields.split(":")
RealItem.new(name: fields[0], price: fields[1].to_i, weight: fields[2].to_i)
end
end
class VirtualItem < Item
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.