Class: MemoryDb::Db

Inherits:
Base
  • Object
show all
Defined in:
lib/memorydb/db.rb

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
  @id = 0
  @store = {}
  @primary_key = options[:primary_key]
end

Instance Method Details

#create!(attrs = {}) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/memorydb/db.rb', line 36

def create!(attrs={})
  _id = id
  attrs = model_or_hash_as_attrs(attrs)
  verify_attributes!(attrs)
  attributes = attrs.merge(primary_key => _id)
  store!(_id, attributes)
  model_klass.new(attributes)
end

#execute_count(query) ⇒ Object



88
89
90
# File 'lib/memorydb/db.rb', line 88

def execute_count(query)
  execute_find(query).size
end

#execute_find(query) ⇒ Object



83
84
85
86
# File 'lib/memorydb/db.rb', line 83

def execute_find(query)
  models = raw_find(query)
  models.map { |h| model_klass.new(h) }
end

#execute_remove!(query) ⇒ Object



92
93
94
95
96
# File 'lib/memorydb/db.rb', line 92

def execute_remove!(query)
  execute_find(query).each do |model|
    remove_model!(model)
  end
end

#find_by_id(id) ⇒ Object



67
68
69
# File 'lib/memorydb/db.rb', line 67

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.



74
75
76
77
78
79
80
81
# File 'lib/memorydb/db.rb', line 74

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

#update!(model_or_id, attributes = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/memorydb/db.rb', line 45

def update!(model_or_id, attributes={})
  attributes ||= {}
  model = case
          when 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.attributes.merge(attributes_without_pkey(attributes))
  store!(model.send(primary_key), updated_attrs)
  model_klass.new(updated_attrs)
end