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.



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

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

Used to initiate the smart chaining logic.



21
22
23
24
# File 'lib/activejabber.rb', line 21

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

Instance Method Details

#generate_hashObject

Creates a random hash used to uniquely identify each method.



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

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

#jabberObject

Returns memoizes and returns a Jabber object, will try to reconnect if disconnected.



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

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

Sends a request to the client, path should be formatted like “/users” and opts may include a :args (a string) and :timeout (in seconds) keys.



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 26

def request(path, opts)
  hash = self.generate_hash
  message = hash + ':' + path.gsub(/\?$/, '')
  if opts[:args]
    message += ('?' + opts[:args])
  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