Class: Atig::Stream

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/atig/stream.rb

Defined Under Namespace

Classes: APIFailed

Instance Method Summary collapse

Methods included from ExceptionUtil

daemon, safe

Constructor Details

#initialize(context, user, password) ⇒ Stream

Returns a new instance of Stream.



16
17
18
19
20
21
# File 'lib/atig/stream.rb', line 16

def initialize(context, user, password)
  @log      = context.log
  @opts     = context.opts
  @user     = user
  @password = password
end

Instance Method Details

#api_baseObject



63
64
65
# File 'lib/atig/stream.rb', line 63

def api_base
  URI(@opts.stream_api_base)
end

#watch(path, query = {}, &f) ⇒ 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
53
54
55
56
57
58
59
60
61
# File 'lib/atig/stream.rb', line 23

def watch(path, query={}, &f)
  path.sub!(%r{\A/+}, "")

  uri = api_base
  uri.path += path
  uri.path += ".json"
  uri.query = query.to_query_str unless query.empty?

  @log.debug [uri.to_s]

  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Post.new uri.request_uri
    request.basic_auth @user, @password

    http.request(request) do |response|
      unless response.code == '200' then
        raise APIFailed,"#{response.code} #{response.message}"
      end

      begin
        buffer = ''
        response.read_body do |chunk|
          next if chunk.chomp.empty?
          buffer << chunk.to_s

          if buffer =~ /\A(.*)\n/ then
            text = $1
            unless text.strip.empty?
              f.call TwitterStruct.make(JSON.parse(text))
            end
            buffer = ''
          end
        end
      rescue => e
        raise APIFailed,e.to_s
      end
    end
  end
end