Module: Adhd::DbUpdateNotifier

Defined in:
lib/adhd/reactor.rb

Overview

A notifier client that makes a long-running request to a CouchDB instance on a socket and continually sends any update notifications that it receives back to its @node.

Instance Method Summary collapse

Instance Method Details

#initialize(db_name, conn_obj) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/adhd/reactor.rb', line 38

def initialize(db_name, conn_obj)
  puts "Db update notifier start..."
  @db_name = db_name
  @conn_obj = conn_obj
  @buffer = ""
  conn_obj.connection_inside = self # We tell the outer object who we are
end

#post_initObject

Makes a long-running request to a CouchDB instance’s _changes URL.



48
49
50
51
52
53
# File 'lib/adhd/reactor.rb', line 48

def post_init
  # NOTE: full domain name needed for virtual hosting
  req = "GET #{@conn_obj.base_url}/#{@db_name}/_changes?feed=continuous&heartbeat=5000\r\n\r\n"
  puts req
  send_data req
end

#receive_data(data) ⇒ Object

Shoots update notifications from CouchDB to the @conn.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/adhd/reactor.rb', line 57

def receive_data data
  # puts "received_data: #{data}"
  # puts "||#{data}||length=#{data.length}||#{data.dump}||"

  @buffer += data # Add the data to the current buffer
  updates = []
  if @buffer =~ /(\{[^\n]+\}\n)/
    updates += ($~.to_a)[1..-1]
    # Trim the buffer to $_.end(0)
    @buffer = @buffer[$~.end(0)..-1]
  end

  # Regexp for JSON updates is /\{[\n]\}+/
  updates.each do |json_event|
    @conn_obj.event_handler(json_event) unless data == "\n"
  end
end