/
search_results.rb
77 lines (68 loc) · 2.11 KB
/
search_results.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
require 'cgi'
require 'twitter/enumerable'
require 'twitter/rest/request'
require 'twitter/utils'
require 'uri'
module Twitter
class SearchResults
include Twitter::Enumerable
include Twitter::Utils
# @return [Hash]
attr_reader :attrs
alias to_h attrs
alias to_hash to_h
deprecate_alias :to_hsh, :to_hash
# Initializes a new SearchResults object
#
# @param request [Twitter::REST::Request]
# @return [Twitter::SearchResults]
def initialize(request)
@client = request.client
@request_method = request.verb
@path = request.path
@options = request.options
@collection = []
self.attrs = request.perform
end
private
# @return [Boolean]
def last?
!next_page?
end
# @return [Boolean]
def next_page?
!!@attrs[:search_metadata][:next_results] unless @attrs[:search_metadata].nil?
end
# Returns a Hash of query parameters for the next result in the search
#
# @note Returned Hash can be merged into the previous search options list to easily access the next page.
# @return [Hash] The parameters needed to fetch the next page.
def next_page
query_string_to_hash(@attrs[:search_metadata][:next_results]) if next_page?
end
# @return [Hash]
def fetch_next_page
response = Twitter::REST::Request.new(@client, @request_method, @path, next_page).perform
self.attrs = response
end
# @param attrs [Hash]
# @return [Hash]
def attrs=(attrs)
@attrs = attrs
@attrs.fetch(:statuses, []).collect do |tweet|
@collection << Tweet.new(tweet)
end
@attrs
end
# Converts query string to a hash
#
# @param query_string [String] The query string of a URL.
# @return [Hash] The query string converted to a hash (with symbol keys).
# @example Convert query string to a hash
# query_string_to_hash("foo=bar&baz=qux") #=> {:foo=>"bar", :baz=>"qux"}
def query_string_to_hash(query_string)
query = CGI.parse(URI.parse(query_string).query)
Hash[query.collect { |key, value| [key.to_sym, value.first] }]
end
end
end