Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

em-mongo examples?

Looking to use em-mongo for a text analyzer script which loads text from db, analyzes it, flags keywords and updates the db.

Would love to see some examples of em-mongo in action. Only one I could find was on github em-mongo repo.

   require 'em-mongo'

   EM.run do
     db = EM::Mongo::Connection.new.db('db')
     collection = db.collection('test')
     EM.next_tick do
       doc = {"hello" => "world"}
       id = collection.insert(doc)
       collection.find('_id' => id]) do |res|
         puts res.inspect
         EM.stop
       end
       collection.remove(doc)
     end
   end
like image 269
sent-hil Avatar asked Nov 06 '22 00:11

sent-hil


1 Answers

You don't need the next_tick method, that is em-mongo doing for you. Define callbacks, that are executed if the db actions are done. Here is a skeleton:

class NonBlockingFetcher
  include MongoConfig

  def initialize
    configure
    @connection = EM::Mongo::Connection.new(@server, @port)
    @collection = init_collection(@connection)
  end

  def fetch(value)
    mongo_cursor = @collection.find({KEY => value.to_s})
    response = mongo_cursor.defer_as_a

    response.callback do |documents|
      # foo
      # get one document
      doc = documents.first
    end

    response.errback do |err|
      # foo
    end

  end
end
like image 86
mosen Avatar answered Nov 09 '22 08:11

mosen