|
1 | 1 | # frozen_string_literal: true |
2 | 2 |
|
3 | | -require 'json' |
4 | | - |
5 | 3 | module Tweetkit |
6 | 4 | module Response |
7 | | - class Tweets |
8 | | - include Enumerable |
9 | | - |
10 | | - attr_accessor :annotations, :connection, :context_annotations, :entity_annotations, :expansions, :fields, :meta, :options, :original_response, :response, :tweets, :twitter_request |
11 | | - |
12 | | - def initialize(response, **options) |
13 | | - parse! response, **options |
14 | | - end |
15 | | - |
16 | | - def parse!(response, **options) |
17 | | - parse_response response |
18 | | - extract_and_save_tweets |
19 | | - return unless @tweets |
20 | | - |
21 | | - extract_and_save_meta |
22 | | - extract_and_save_expansions |
23 | | - extract_and_save_options(**options) |
24 | | - extract_and_save_request |
25 | | - end |
26 | | - |
27 | | - def parse_response(response) |
28 | | - @response = response.body |
29 | | - end |
30 | | - |
31 | | - def extract_and_save_tweets |
32 | | - if (data = @response['data']) |
33 | | - if data.is_a?(Array) |
34 | | - @tweets = @response['data'].collect { |tweet| Tweet.new(tweet) } |
35 | | - else |
36 | | - @tweets = [Tweet.new(@response['data'])] |
37 | | - end |
38 | | - else |
39 | | - @tweets = nil |
40 | | - end |
41 | | - end |
42 | | - |
43 | | - def extract_and_save_meta |
44 | | - @meta = Meta.new(@response['meta']) |
45 | | - end |
46 | | - |
47 | | - def extract_and_save_expansions |
48 | | - @expansions = Expansions.new(@response['includes']) |
49 | | - end |
50 | | - |
51 | | - def extract_and_save_options(**options) |
52 | | - @options = options |
53 | | - end |
54 | | - |
55 | | - def extract_and_save_request |
56 | | - @connection = @options[:connection] |
57 | | - @twitter_request = @options[:twitter_request] |
58 | | - end |
59 | | - |
60 | | - def each(*args, &block) |
61 | | - tweets.each(*args, &block) |
62 | | - end |
63 | | - |
64 | | - def last |
65 | | - tweets.last |
66 | | - end |
67 | | - |
68 | | - def tweet |
69 | | - tweets.first |
70 | | - end |
71 | | - |
72 | | - def next_page |
73 | | - connection.params.merge!({ next_token: meta.next_token }) |
74 | | - response = connection.get(twitter_request[:previous_url]) |
75 | | - parse! response, |
76 | | - connection: connection, |
77 | | - twitter_request: { |
78 | | - previous_url: twitter_request[:previous_url], |
79 | | - previous_query: twitter_request[:previous_query] |
80 | | - } |
81 | | - self |
82 | | - end |
83 | | - |
84 | | - def prev_page |
85 | | - connection.params.merge!({ previous: meta.previous_token }) |
86 | | - response = connection.get(twitter_request[:previous_url]) |
87 | | - parse! response, |
88 | | - connection: connection, |
89 | | - twitter_request: { |
90 | | - previous_url: twitter_request[:previous_url], |
91 | | - previous_query: twitter_request[:previous_query] |
92 | | - } |
93 | | - self |
94 | | - end |
95 | | - end |
96 | 5 | end |
97 | 6 | end |
0 commit comments