Class: MemoryDb::Db
Instance Method Summary
collapse
Methods inherited from Base
#filter, #find, #remove!, #remove_by_id!
Constructor Details
#initialize(model_klass, options = {}) ⇒ Db
Returns a new instance of Db.
28
29
30
31
32
33
|
# File 'lib/memorydb/db.rb', line 28
def initialize(model_klass, options={})
@model_klass = model_klass
@id = 0
@store = {}
@primary_key = options[:primary_key]
end
|
Instance Method Details
#create!(given = {}) ⇒ Object
35
36
37
38
39
40
41
|
# File 'lib/memorydb/db.rb', line 35
def create!(given={})
_id = id
attrs = model_or_hash_as_attrs(given)
attributes = attrs.merge(primary_key => _id)
store!(_id, attributes)
return_model_or_hash(attributes)
end
|
#execute_count(query) ⇒ Object
98
99
100
|
# File 'lib/memorydb/db.rb', line 98
def execute_count(query)
execute_find(query).size
end
|
#execute_find(query) ⇒ Object
89
90
91
92
93
94
95
96
|
# File 'lib/memorydb/db.rb', line 89
def execute_find(query)
models = raw_find(query)
if model_klass
models.map { |h| model_klass.new(h) }
else
models
end
end
|
#execute_remove!(query) ⇒ Object
102
103
104
105
106
|
# File 'lib/memorydb/db.rb', line 102
def execute_remove!(query)
execute_find(query).each do |model|
remove_model!(model)
end
end
|
#find_by_id(id) ⇒ Object
73
74
75
|
# File 'lib/memorydb/db.rb', line 73
def find_by_id(id)
find.eq(primary_key, id).first
end
|
#raw_find(query) ⇒ Object
These methods are called by the cursor. Do not call them directly. Or call them. Whatever. Either one.
80
81
82
83
84
85
86
87
|
# File 'lib/memorydb/db.rb', line 80
def raw_find(query)
models = all_models
models = apply_transforms models, query[:transforms]
models = filter_models models, query[:filters]
models = sort_models models, query[:sorts]
models = offset_models models, query[:offset]
models = limit_models models, query[:limit]
end
|
#return_model_or_hash(attrs) ⇒ Object
43
44
45
46
47
48
49
|
# File 'lib/memorydb/db.rb', line 43
def return_model_or_hash(attrs)
if model_klass
model_klass.new(attrs)
else
attrs
end
end
|
#update!(model_or_id, attributes = {}) ⇒ Object
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/memorydb/db.rb', line 51
def update!(model_or_id, attributes={})
attributes ||= {}
model_or_hash = case
when model_klass && model_or_id.is_a?(model_klass)
if model = find_by_id(model_or_id.send(primary_key))
model_or_id
else
raise ArgumentError.new("Could not update record with id: #{model_or_id.send(primary_key)} because it does not exist") unless model
end
else
if model = find_by_id(model_or_id)
model
else
raise ArgumentError.new("Could not update record with id: #{model_or_id} because it does not exist") unless model
end
end
updated_attrs = model_or_hash_as_attrs(model_or_hash).merge(attributes_without_pkey(attributes))
store!(model_or_hash[primary_key], updated_attrs)
return_model_or_hash(updated_attrs)
end
|