Class: ActiveJabber::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/activejabber.rb

Defined Under Namespace

Classes: Request

Instance Method Summary collapse

Constructor Details

#initialize(username, password) ⇒ Base

Returns a new instance of Base.



15
16
17
18
# File 'lib/activejabber.rb', line 15

def initialize(username, password)
  @username = username
  @password = password
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



19
20
21
22
# File 'lib/activejabber.rb', line 19

def method_missing(method, *args)
  request_parts = []
  Base::Request.new(self, nil, request_parts).send(method, *args)
end

Instance Method Details

#generate_hashObject



53
54
55
# File 'lib/activejabber.rb', line 53

def generate_hash
  ActiveSupport::SecureRandom.hex(8) # Generates 16 character hexdecimal string.
end

#jabberObject



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/activejabber.rb', line 3

def jabber
  if @jabber
    if @jabber.connected?
      return @jabber
    else
      @jabber.reconnect
    end
  else
    @jabber = Jabber::Simple.new(@username, @password)
  end
  return @jabber
end

#request(path, opts) ⇒ Object



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
# File 'lib/activejabber.rb', line 23

def request(path, opts)
  hash = self.generate_hash
  message = hash + ':' + path.gsub(/\?$/, '')
  if opts[:args]
    message += ('?' + opts[:args])
  end
  unless opts[:timeout]
    opts[:timeout] = 5.0
  end
  
  self.jabber.deliver(Jabber::JID.new('[email protected]'), message)
  start = Time.now
  while (Time.now - start) < opts[:timeout]
    self.jabber.received_messages do |msg|
      if msg.body.strip.starts_with?(hash) and msg.from.to_s.strip.starts_with?('[email protected]')
        parts = msg.body.strip.split(':', 3)
        data = (parts[2].nil? ? '' : parts[2].strip)
        if opts[:format] == :json
          data = ActiveSupport::JSON.decode(data)
        end
        response = {:status => parts[1].to_i, :data => data}
        response[:latency] = (Time.now - start)
        return response
      end
    end
  end
  if (Time.now - start) >= opts[:timeout]
    return {:status => 408, :data => '', :latency => (Time.now - start)} # Request timeout
  end
end