Милена обнови решението на 01.12.2016 23:14 (преди около 8 години)
+
+module DataModelExceptions
+ class DeleteUnsavedRecordError < StandartError
+ end
+end
+
+class DataStore
+ def storage
+ @store
+ end
+
+ def initialize
+ @store = {}
+ end
+
+ def create(model)
+ end
+
+ def find(model)
+ end
+
+ def update(model_id)
+ end
+
+ def delete(model)
+ end
+end
+
+class ArrayStore < DataStore
+ attr_reader :store
+
+ def initialize
+ @store = []
+ end
+
+ def create(model)
+ @store.push(model)
+ end
+
+ def find(model)
+ @store.find(model)
+ end
+
+ def update(model_id, model)
+ @store.find { |id| id == model_id }.first = model
+ end
+
+ def delete(model)
+ @store.delete(model)
+ end
+end
+
+class HashStore < DataStore
+ attr_reader :store
+ @id = 0
+
+ def initialize(store)
+ @store = store
+ end
+
+ def create(model)
+ id += 1
+ @store[id] = model
+ end
+
+ def find(model)
+ @store.select { |_, v| v == model }
+ end
+
+ def update(model_id, model)
+ @store[model_id] = model
+ end
+
+ def delete(model)
+ @store.each { |item| item == model }.delete(model)
+ end
+end
+
+class DataModelExceptions
+ include DataModelExceptions
+
+ attr_reader :id
+ @id = 1
+
+ def initialize(hash = nil)
+ return @attributes = {} unless hash
+ @attributes = {}
+ hash.each do |key, value|
+ @attributes[key] = value
+ end
+ end
+
+ def self.data_store(store)
+ @data_store = store
+ end
+
+ def save
+ if @id
+ puts @data_store.class
+ @data_store.create(@attributes)
+ else
+ @data_store.update(@id, @attributes)
+ end
+ self
+ end
+
+ def delete
+ raise DeleteUnsavedRecordError unless @id
+ @data_store.delete(self.to_h)
+ end
+
+ def self.==(other)
+ self.instance_of? == other.instance_of? &&
+ @id == other.id ||
+ self.equal?(other)
+ end
+
+ def self.attributes(*args)
+ if args.empty?
+ @attributes.to_a.map { |atr| atr.to_sym }
+ else
+ @attributes = args.to_a
+ end
+ end
+end