Class: StoreTasks

Inherits:
Volt::TaskHandler show all
Defined in:
app/volt/tasks/store_tasks.rb

Instance Method Summary collapse

Methods inherited from Volt::TaskHandler

inherited, known_handlers, method_missing

Constructor Details

#initialize(channel = nil, dispatcher = nil) ⇒ StoreTasks

Returns a new instance of StoreTasks.



4
5
6
7
# File 'app/volt/tasks/store_tasks.rb', line 4

def initialize(channel = nil, dispatcher = nil)
  @channel = channel
  @dispatcher = dispatcher
end

Instance Method Details

#dbObject



9
10
11
# File 'app/volt/tasks/store_tasks.rb', line 9

def db
  @@db ||= Volt::DataStore.fetch
end

#delete(collection, id) ⇒ Object



64
65
66
67
68
# File 'app/volt/tasks/store_tasks.rb', line 64

def delete(collection, id)
  db[collection].remove('_id' => id)

  QueryTasks.live_query_pool.updated_collection(collection, @channel)
end

#model_values_and_errors(collection, data) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/volt/tasks/store_tasks.rb', line 13

def model_values_and_errors(collection, data)
  model_name = collection.singularize.camelize

  # TODO: Security check to make sure we have a valid model
  # and don't load classes we shouldn't
  begin
    model_class = Object.send(:const_get, model_name)
  rescue NameError => e
    model_class = nil
  end

  if model_class
    model = model_class.new(data)
    return model.to_h, model.errors
  end

  [data, {}]
end

#save(collection, data) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/volt/tasks/store_tasks.rb', line 32

def save(collection, data)
  data = data.symbolize_keys
  values, errors = model_values_and_errors(collection, data)

  if errors.size == 0
    # id = BSON::ObjectId(values[:_id])
    id = values[:_id]

    # Try to create
    # TODO: Seems mongo is dumb and doesn't let you upsert with custom id's
    begin
      # values['_id'] = BSON::ObjectId('_id') if values['_id']
      db[collection].insert(values)
    rescue Mongo::OperationFailure => error
      # Really mongo client?
      if error.message[/^11000[:]/]
        # Update because the id already exists
        update_values = values.dup
        update_values.delete(:_id)
        db[collection].update({ _id: id }, update_values)
      else
        return { error: error.message }
      end
    end

    QueryTasks.live_query_pool.updated_collection(collection, @channel)
    return {}
  else
    return errors
  end
end