Class: StoreTasks

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of StoreTasks.



5
6
7
8
9
10
11
# File 'app/volt/tasks/store_tasks.rb', line 5

def initialize(channel=nil, dispatcher=nil)
  @@mongo_db ||= Mongo::MongoClient.new("localhost", 27017)
  @@db ||= @@mongo_db.db("development")
  
  @channel = channel
  @dispatcher = dispatcher
end

Instance Method Details

#dbObject



13
14
15
# File 'app/volt/tasks/store_tasks.rb', line 13

def db
  @@db
end

#delete(collection, id) ⇒ Object



54
55
56
57
58
59
# File 'app/volt/tasks/store_tasks.rb', line 54

def delete(collection, id)
  puts "DELETE: #{collection.inspect} - #{id.inspect}"
  @@db[collection].remove('_id' => id)
  
  ChannelTasks.send_message_to_channel("#{collection}-removed", ['removed', nil, id], @channel)
end

#find(collection, scope, query = nil) ⇒ Object



47
48
49
50
51
52
# File 'app/volt/tasks/store_tasks.rb', line 47

def find(collection, scope, query=nil)
  results = @@db[collection].find(scope).to_a.map {|item| item.symbolize_keys }
  puts "FIND: #{collection.inspect} - #{scope} - #{results.inspect}"
  
  return results
end

#save(collection, data) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/volt/tasks/store_tasks.rb', line 17

def save(collection, data)
  puts "Insert: #{data.inspect} on #{collection.inspect}"
  
  data = data.symbolize_keys
  id = data[:_id]

  # Try to create
  # TODO: Seems mongo is dumb and doesn't let you upsert with custom id's
  begin
    @@db[collection].insert(data)
    
    # Message that we inserted a new item
    puts "SENDING DATA: #{data.inspect}"
    ChannelTasks.send_message_to_channel("#{collection}-added", ['added', nil, collection, data], @channel)
  rescue Mongo::OperationFailure => error
    # Really mongo client?
    if error.message[/^11000[:]/]
      # Update because the id already exists
      update_data = data.dup
      update_data.delete(:_id)
      @@db[collection].update({:_id => id}, update_data)
    else
      raise
    end
  end
  

  ChannelTasks.send_message_to_channel("#{collection}##{id}", ['changed', nil, id, data], @channel)
end