Class: SPSChatCli

Inherits:
SPSChat
  • Object
show all
Defined in:
lib/sps_chat-cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(host: '127.0.0.1', port: '8080', userid: 'user' + (0..1000).to_a.sample.to_s, room: '', typing_mode: false) ⇒ SPSChatCli

Returns a new instance of SPSChatCli.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/sps_chat-cli.rb', line 15

def initialize(host: '127.0.0.1', port: '8080', \
                userid: 'user' + (0..1000).to_a.sample.to_s, room: '', typing_mode: false)

  super(host: host, port: port, userid: userid, room: room)
  
  @userid, @typing_mode = userid, typing_mode
  terminated = false
  @user, @history = {}, []
  
  sleep 1
  print "\r\n"

  loop do

    @s = ''

    print "\r#{userid}> "

    begin

      c = $stdin.getch
      (terminated = true; break) if c == CTRLC
      
      if typing_mode then
        
        unless c == "\r" then
          typing c 
        else
          c = "\n"            
          @history << "#{userid}> " + @s
          send @s            
        end
      end

      @s = savebuffer @s, c
      print "\r#{@userid}>  " + ' ' * @s.length if c == BACKSPACE
      print "\r#{@userid}> " + @s 
      
    end until c == "\r" or c == "\n" or terminated

    break if terminated
    
    unless typing_mode then
      print "\r" + @userid + '> ' + @s + "\n"
      send @s
    end

  end 
end

Instance Method Details

#onincoming(sender, msg, typing_mode = false) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/sps_chat-cli.rb', line 65

def onincoming(sender, msg, typing_mode=false)    
  
  if @typing_mode then

    if msg.length <= 1 then
      c = msg                

      @user[sender] ||= ''
      @user[sender] = savebuffer @user[sender], c             
      print "\e[H\e[2J"
      print "\r\n" + @history.join("\r\n") + "\r\n"
    else        
      c = "\n"
      @history << "#{sender}> " + @user[sender]
      @user[sender] = ''
    end
 
    @user.each do |u, s|
      print "\r\r#{u}> " + s  + "\n" unless s.empty?
    end

    print "\r#{@userid}> " + @s  
    
  else
    print "\r%s> %s\n" % [sender, msg]
    print "\r%s> " % @userid
  end
end

#savebuffer(s, c = '') ⇒ Object



94
95
96
97
98
99
# File 'lib/sps_chat-cli.rb', line 94

def savebuffer(s, c='')
  
  c == BACKSPACE ?  s.chop! : s += c 
  
  return s
end