Module: JsChat::Storage::MongoDriver

Defined in:
lib/jschat/storage/mongo.rb

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


50
51
52
53
54
55
56
57
# File 'lib/jschat/storage/mongo.rb', line 50

def self.available?
  return unless Object.const_defined?(:Mongo)
  connect!
rescue
  p $!
  puts 'Failed to connect to mongo'
  false
end

.connect!Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/jschat/storage/mongo.rb', line 8

def self.connect!
  @db = Mongo::Connection.new(ServerConfig['db_host'], ServerConfig['db_port'], :slave_ok => true).db(ServerConfig['db_name'])
  if ServerConfig['db_username'] and ServerConfig['db_password']
    if @db.authenticate(ServerConfig['db_username'], ServerConfig['db_password'])
      true
    else
      raise 'Bad Mongo username or password'
    end
  else
    true
  end
end

.delete_user(user) ⇒ Object



46
47
48
# File 'lib/jschat/storage/mongo.rb', line 46

def self.delete_user(user)
  @db['users'].remove user
end

.find_user(options) ⇒ Object

TODO: use twitter oauth for the key



38
39
40
# File 'lib/jschat/storage/mongo.rb', line 38

def self.find_user(options)
  @db['users'].find_one(options)
end

.lastlog(number, room) ⇒ Object



26
27
28
# File 'lib/jschat/storage/mongo.rb', line 26

def self.lastlog(number, room)
  @db['events'].find({ :room => room }, { :limit => number, :sort => ['time', Mongo::DESCENDING] }).to_a.reverse
end

.log(message, room) ⇒ Object



21
22
23
24
# File 'lib/jschat/storage/mongo.rb', line 21

def self.log(message, room)
  message['room'] = room
  @db['events'].insert(message)
end

.save_user(user) ⇒ Object



42
43
44
# File 'lib/jschat/storage/mongo.rb', line 42

def self.save_user(user)
  @db['users'].save user
end

.search(query, room, limit) ⇒ Object



30
31
32
33
34
35
# File 'lib/jschat/storage/mongo.rb', line 30

def self.search(query, room, limit)
  query = /\b#{query}\b/i
  @db['events'].find({ 'message.message' => query, 'room' => room },
    { :limit => limit, :sort => ['time', Mongo::DESCENDING] }
  ).to_a.reverse
end