Class: UsageTracker::Adapters::Couchdb

Inherits:
Object
  • Object
show all
Defined in:
lib/usage_tracker/adapters/couchdb.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(settings) ⇒ Couchdb

Returns a new instance of Couchdb.



9
10
11
12
13
14
15
16
# File 'lib/usage_tracker/adapters/couchdb.rb', line 9

def initialize (settings)
  @database =
    CouchRest.database!(settings.database).tap do |db|
      db.info
    end
rescue Errno::ECONNREFUSED, RestClient::Exception => e
  raise "Unable to connect to database #{settings.database}: #{e.message}"
end

Instance Attribute Details

#databaseObject

Returns the value of attribute database.



8
9
10
# File 'lib/usage_tracker/adapters/couchdb.rb', line 8

def database
  @database
end

Instance Method Details

#make_idObject

Timestamp as _id has the advantage that documents are sorted automatically by CouchDB.

Eventual duplication (multiple servers) is (possibly) avoided by adding a random digit at the end.



29
30
31
# File 'lib/usage_tracker/adapters/couchdb.rb', line 29

def make_id
  Time.now.to_f.to_s.ljust(16, '0') + rand(10).to_s
end

#save_doc(doc) ⇒ Object



18
19
20
21
# File 'lib/usage_tracker/adapters/couchdb.rb', line 18

def save_doc (doc)
  doc['_id'] = make_id if doc['_id'].nil?
  @database.save_doc(doc)
end