Skip to content

Instantly share code, notes, and snippets.

@Timrael

Timrael/add_to_cart.rb

Forked from anonymous/add_to_cart.rb
Last active Dec 15, 2015
Embed
What would you like to do?
require_relative "inet2"
puts ARGV
cart = Cart.new(ARGV.delete_at(0))
ARGV.each do |argument|
@items.each { |item| cart.add_expensive_item(item) if argument == item.name }
end
cart.save_to_file
class Cart
attr_reader :items
include ItemContainer
def initialize(owner)
@items = []
@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
@items = []
File.readlines("#{@owner}_cart.txt").each {|item| @items << item.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
@@discount + 0.1
else
@@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}. Price: #{self.price}, Weight: #{self.weight}"
end
def valid?
!self.price.nil?
end
private
def tax
cost_tax + type_tax
end
def type_tax
if self.class == VirtualItem
1
else
2
end
end
def cost_tax
if @real_price > 5
@real_price * 0.2
else
@real_price * 0.1
end
end
end
module ItemContainer
module ClassMethods
def min_price
50
end
end
module InstantMethods
def add_expensive_item(item)
unless item.price < self.class.min_price
@items.push item
end
end
def remove_item_from_tail
@items.pop
end
def validate
@items.each{ |item| puts "Item has no price" if item.valid? }
end
def delete_invalid_items
@items.delete_if { |item| !item.valid? }
end
def count_valid_items
@items.select{ |item| item.valid? }.count
end
end
def self.included(base)
base.extend ClassMethods
base.class_eval do
include InstantMethods
end
end
end
class RealItem < Item
attr_accessor :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.