Module: DashFu

Defined in:
lib/dash-fu.rb

Overview

Use me to push data to Dash-fu in real time.

The only configuration you need is setting the API key in config/environments/production.rb:

DashFu.api_key = "<your API key>"

You only want to push data in production, so make sure the API key is only set in production environment. Calls to created/active with no API key are simply ignored.

You can send events by calling DashFu.push with UID and event, or using the specialized created and active methods.

For example, to assign a user to a cohort, we’re going to notify Dash-fu whenever an acount gets created:

class User < ActiveRecord::Model
  after_create do
    DashFu.created id
  end
end

In this example, we consider a user active whenever they post a status update, and notify Dash-fu accordingly:

class StatusUpdate < ActiveRecord::Model
  after_create do
    DashFu.active id
  end
end

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.api_keyObject

Set the API key with:

DashFu.api_key = "<your API key>"


46
47
48
# File 'lib/dash-fu.rb', line 46

def api_key
  @api_key
end

.hostObject

DashFu.host is set by default, this is only useful for testing.



42
43
44
# File 'lib/dash-fu.rb', line 42

def host
  @host
end

.portObject

DashFu.host is set by default, this is only useful for testing.



42
43
44
# File 'lib/dash-fu.rb', line 42

def port
  @port
end

Class Method Details

.active(uid) ⇒ Object

Records that a user has been active in the app.



49
50
51
# File 'lib/dash-fu.rb', line 49

def active(uid)
  push uid, "active"
end

.closeObject

Close connection. If you like crossing your t’s you can call this when the app shutsdown.



61
62
63
64
65
66
67
# File 'lib/dash-fu.rb', line 61

def close
  @mutex.synchronize do
    socket, @socket = @socket, nil
    socket.close if socket
  end
rescue Exception
end

.created(uid) ⇒ Object

Records that a new user account has been created (associate them with cohort).



55
56
57
# File 'lib/dash-fu.rb', line 55

def created(uid)
  push uid, "created"
end

.push(uid, event) ⇒ Object

Push update for the specified user ID and event. Or you can use active/created.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/dash-fu.rb', line 71

def push(uid, event)
  return unless @api_key
  if socket = @socket
    socket.sendmsg_nonblock "POST /v1/push?api_key=#{@api_key}&uid=#{uid}&event=#{event} HTTP/1.1\r\nHost: #{@host}\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n", 0
    socket.recv_nonblock 512 rescue nil
  else
    Thread.new do
      @mutex.synchronize do
        @socket ||= TCPSocket.open(@host, @port || 80)
      end
      push uid, event
    end
  end
rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ETIMEDOUT
  close
  retry
rescue Errno::ECONNREFUSED, Errno::ENETUNREACH
  # No @socket so we'll try to connect next time
end