Петър обнови решението на 30.11.2016 10:51 (преди около 8 години)
+class ArrayStore
+ @storage
+
+ def initialize
+ @storage = []
+ end
+
+ def create(record)
+ @storage.push(record)
+ end
+
+ def find(request)
+ @storage.select do |hash|
+ request.to_a.each do |pair|
+ hash.to_a.include?(pair)
+ end
+ end
+ end
+
+ def update(id_number, new_attributes)
+ updated_index = @storage.find { |hash| hash[:id] = id_number }
+ @storage[updated_index].merge!(new_attributes) unless updated_index.nil?
+ end
+
+ def delete(request)
+ @storage.delete_if do |hash|
+ request.to_a.each do |pair|
+ hash.to_a.include?(pair)
+ end
+ end
+ end
+
+ def id?(id)
+ @storage.any? { |hash| hash.to_a.include?([:id, id]) }
+ end
+end
+
+class HashStore
+ @storage
+
+ def initialize
+ @storage = {}
+ end
+
+ def create(record)
+ @storage[record[:id]] = record
+ end
+
+ def find(request)
+ @storage.values.select do |hash|
+ request.to_a.each do |pair|
+ hash.to_a.include?(pair)
+ end
+ end
+ end
+
+ def update(id_number, new_attributes)
+ # ...
+ end
+
+ def delete(request)
+ # ...
+ end
+end
+
+class DataModel
+ self.class.instance_variable_set(:@store, nil)
+ self.class.instance_variable_set(:@free_id, 1)
+ @attributes_hash
+ @id
Тези четирите реда какво правят тук?
+
+ def initialize(attributes_values = {})
+ @attributes_hash.each_key do |key|
+ @attributes_hash[key] = attributes_values[key]
+ end
+ @id = attributes_values[:id]
+ end
+
+ def save
+ unless @store.nil?
+ if id.nil?
+ id = @free_id
+ @free_id += 1
+ @store.create(attributes_hash.merge({id: id}))
+ else
+ @store.update(id, attributes_hash)
+ end
+ end
+ end
+
+ def delete
+ @store.delete({id: id}) unless @store.nil? || id.nil?
+ # Exception needed
+ end
+
+ def ==(other)
+ self.equal?(other) || (self.class == other.class && id.nil? && id == other.id)
+ end
+
+ def self.attributes(*attributes_names)
+ attributes_names.each do |attribute|
+ attributes_hash[attribute] = nil
+ end
+ create_accessors_and_finder
+ end
+
+ def self.data_store(store_object = nil)
+ @store = store_object unless store_object.nil?
+ @store
+ end
+
+ def self.where(request)
+ @store.find(request).map { |hash| self.class.new(hash) }
+ end
+
+ private
+
+ def create_accessors_and_finder
+ attributes_hash.each_key do |key|
+ define_method (key) { attributes_hash[key] }
+ define_method ("#{key}=".to_sym) { |value| attributes_hash[key] = value }
+ finder = "find_by_#{key}".to_sym
+ define_singleton_method (finder) { |value| @store.find({key => value}) }
+ end
+ end
+end