Class: Atig::Stream

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

Defined Under Namespace

Classes: APIFailed

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ExceptionUtil

daemon, safe

Constructor Details

#initialize(context, channel, access) ⇒ Stream

Returns a new instance of Stream.



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

def initialize(context, channel, access)
  @log      = context.log
  @opts     = context.opts
  @channel  = channel
  @access   = access
end

Instance Attribute Details

#channelObject (readonly)

Returns the value of attribute channel.



14
15
16
# File 'lib/atig/stream.rb', line 14

def channel
  @channel
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



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 24

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]

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request.oauth!(http, @access.consumer, @access)
  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