Class: MemoryDb::Db
Constant Summary
collapse
- DEFAULT_ID =
0
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.
29
30
31
32
33
34
|
# File 'lib/memorydb/db.rb', line 29
def initialize(model_klass, options={})
@model_klass = model_klass
@store = {}
@id = initialize_id(options[:random_id])
@primary_key = options[:primary_key]
end
|
Instance Method Details
#create!(given = {}) ⇒ Object
36
37
38
39
40
41
42
|
# File 'lib/memorydb/db.rb', line 36
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
99
100
101
|
# File 'lib/memorydb/db.rb', line 99
def execute_count(query)
execute_find(query).size
end
|
#execute_find(query) ⇒ Object
90
91
92
93
94
95
96
97
|
# File 'lib/memorydb/db.rb', line 90
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
103
104
105
106
107
|
# File 'lib/memorydb/db.rb', line 103
def execute_remove!(query)
execute_find(query).each do |model|
remove_model!(model)
end
end
|
#find_by_id(id) ⇒ Object
74
75
76
|
# File 'lib/memorydb/db.rb', line 74
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.
81
82
83
84
85
86
87
88
|
# File 'lib/memorydb/db.rb', line 81
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
44
45
46
47
48
49
50
|
# File 'lib/memorydb/db.rb', line 44
def return_model_or_hash(attrs)
if model_klass
model_klass.new(attrs)
else
attrs
end
end
|
#update!(model_or_id, attributes = {}) ⇒ Object
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/memorydb/db.rb', line 52
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
|