summaryrefslogtreecommitdiff
path: root/lib/tapicero/couch_changes.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/tapicero/couch_changes.rb')
-rw-r--r--lib/tapicero/couch_changes.rb59
1 files changed, 45 insertions, 14 deletions
diff --git a/lib/tapicero/couch_changes.rb b/lib/tapicero/couch_changes.rb
index abb451d..3b7da59 100644
--- a/lib/tapicero/couch_changes.rb
+++ b/lib/tapicero/couch_changes.rb
@@ -1,7 +1,21 @@
+require 'couchrest'
+require 'fileutils'
+
module Tapicero
class CouchChanges
- def initialize(stream)
- @stream = stream
+
+ attr_accessor :db
+
+ def initialize(db, seq_filename)
+ @db = db
+ @seq_filename = seq_filename
+ FileUtils.touch(seq_filename)
+ unless File.writable?(seq_filename)
+ raise StandardError.new("Can't access sequence file")
+ end
+ @since = File.read(seq_filename)
+ rescue Errno::ENOENT => e
+ puts "No sequence file found. Starting from scratch"
end
def created(hash = {}, &block)
@@ -12,24 +26,41 @@ module Tapicero
end
end
- def last_seq
- @stream.get "_changes", :limit => 1, :descending => true do |hash|
- return hash[:last_seq]
- end
- end
-
def listen
- @stream.get "_changes", :feed => :continuous, :since => last_seq do |hash|
+ puts "listening..."
+ puts "Starting at sequence #{since}"
+ db.changes :feed => :continuous, :since => since, :heartbeat => 1000 do |hash|
callbacks(hash)
end
end
+ protected
+
+ def since
+ @since ||= 0 # fetch_last_seq
+ end
+
def callbacks(hash)
- #changed
- return if hash[:deleted]
- return unless changes = hash[:changes]
- return created(hash) if changes[0][:rev].start_with?('1-')
- #updated
+ #changed callback
+ return if hash["deleted"] # deleted_callback
+ return unless changes = hash["changes"]
+ created(hash) if changes[0]["rev"].start_with?('1-')
+ store_seq(hash["seq"])
+ #updated callback
+ end
+
+ def store_seq(seq)
+ File.write(@seq_filename, seq)
end
+
+ #
+ # UNUSED: this is useful for only following new sequences.
+ #
+ def fetch_last_seq
+ hash = db.changes :limit => 1, :descending => true
+ puts "starting at seq: " + hash["last_seq"]
+ return hash["last_seq"]
+ end
+
end
end