Class: Blamescope::Server
- Inherits:
-
Object
- Object
- Blamescope::Server
- Defined in:
- lib/blamescope/server.rb
Constant Summary collapse
- TABLE_QUERY =
<<-EOS CREATE TABLE IF NOT EXISTS blamescope ( id serial NOT NULL, email character varying(255), action character varying(255), model character varying(255), attrs json, created_at timestamp without time zone, CONSTRAINT blamescope_pkey PRIMARY KEY (id) ); EOS
Class Method Summary collapse
Instance Method Summary collapse
- #listen(config) ⇒ Object
- #postgres_connection(config) ⇒ Object
- #rabbit_connection(config) ⇒ Object
- #store_event(db, body, time = Time.now.utc) ⇒ Object
Class Method Details
.start(options = {}) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/blamescope/server.rb', line 20 def self.start( = {}) # Parse options optparse = OptionParser.new do |opts| opts. = "Usage: blamescope [options]" opts.on("-d", "--database CONF", "Database connection in format postgres://user:password@host/database") do |d| [:database] = d end opts.on("-r", "--rabbit CONF", "RabbitMQ connection in format amqp://user:pass@host:port/vhost") do |r| [:rabbit] = r end opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| [:verbose] = v end end optparse.parse! if [:database] && [:rabbit] new.listen() else puts optparse end end |
Instance Method Details
#listen(config) ⇒ Object
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/blamescope/server.rb', line 43 def listen(config) rabbit = rabbit_connection(config[:rabbit]) db = postgres_connection(config[:database]) rabbit[:queue].subscribe(block: true) do |delivery_info, properties, body| store_event(db, body) end rescue Interrupt => _ rabbit[:channel].close rabbit[:conn].close end |
#postgres_connection(config) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/blamescope/server.rb', line 67 def postgres_connection(config) config = URI.parse(config) params = {host: config.host, dbname: config.path[1..-1]} params[:user] = config.user if config.user params[:password] = config.password if config.password params[:port] = config.port if config.port conn = PG.connect(params) conn.exec(TABLE_QUERY) conn.prepare("insert_event", "INSERT INTO blamescope (email, action, model, attrs, created_at) VALUES ($1, $2, $3, $4, $5)") return conn end |
#rabbit_connection(config) ⇒ Object
59 60 61 62 63 64 65 |
# File 'lib/blamescope/server.rb', line 59 def rabbit_connection(config) rabbit = Blamescope.rabbit_connection(config) queue = rabbit[:channel].queue("", exclusive: true) queue.bind(rabbit[:exchange]) rabbit[:queue] = queue return rabbit end |
#store_event(db, body, time = Time.now.utc) ⇒ Object
54 55 56 57 |
# File 'lib/blamescope/server.rb', line 54 def store_event(db, body, time = Time.now.utc) event = JSON.parse(body) db.exec_prepared('insert_event', [event['email'], event['action'], event['model'], event['attrs'].to_json, time]) end |