Class: Talker

Inherits:
EM::Connection
  • Object
show all
Defined in:
lib/talker.rb,
lib/talker/cli.rb

Defined Under Namespace

Classes: CLI, Error

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTalker

Returns a new instance of Talker.



27
28
29
# File 'lib/talker.rb', line 27

def initialize
  @users = {}
end

Instance Attribute Details

#roomObject

Returns the value of attribute room.



7
8
9
# File 'lib/talker.rb', line 7

def room
  @room
end

#threadObject

Returns the value of attribute thread.



7
8
9
# File 'lib/talker.rb', line 7

def thread
  @thread
end

#tokenObject

Returns the value of attribute token.



7
8
9
# File 'lib/talker.rb', line 7

def token
  @token
end

Class Method Details

.connect(options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/talker.rb', line 9

def self.connect(options={})
  host = options[:host] || "talkerapp.com"
  port = (options[:port] || 8500).to_i
  room = options[:room].to_i
  token = options[:token]
  
  thread = Thread.new { EM.run } unless EM.reactor_running?
  
  EM.connect host, port, self do |c|
    c.thread = thread
    c.room = room
    c.token = token
    yield c if block_given?
  end
  
  thread.join unless thread.nil?
end

Instance Method Details

#closeObject



72
73
74
# File 'lib/talker.rb', line 72

def close
  close_connection_after_writing
end

#connection_completedObject

EventMachine callbacks



62
63
64
65
# File 'lib/talker.rb', line 62

def connection_completed
  send :type => "connect", :room => @room, :token => @token
  EM.add_periodic_timer(20) { send :type => "ping" }
end

#leaveObject



67
68
69
70
# File 'lib/talker.rb', line 67

def leave
  send :type => "close"
  close
end

#post_initObject



76
77
78
79
# File 'lib/talker.rb', line 76

def post_init
  @parser = Yajl::Parser.new
  @parser.on_parse_complete = method(:event_parsed)
end

#receive_data(data) ⇒ Object



81
82
83
# File 'lib/talker.rb', line 81

def receive_data(data)
  @parser << data
end

#send_message(message, attributes = {}) ⇒ Object



44
45
46
# File 'lib/talker.rb', line 44

def send_message(message, attributes={})
  send({ :type => "message", :content => message }.merge(attributes))
end

#send_private_message(to, message) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/talker.rb', line 48

def send_private_message(to, message)
  if to.is_a?(String)
    user = @users.values.detect { |user| user["name"] == to }
    raise Error, "User #{to} not found" unless user
    user_id = user["id"]
  else
    user_id = to
  end
  send_message message, :to => user_id
end

#unbindObject



85
86
87
88
# File 'lib/talker.rb', line 85

def unbind
  trigger :close
  @thread.kill if @thread
end

#usersObject



40
41
42
# File 'lib/talker.rb', line 40

def users
  @users.values
end