Class: Serel::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/serel/request.rb

Instance Method Summary collapse

Constructor Details

#initialize(type, scoping, qty) ⇒ Request

Returns a new instance of Request.



3
4
5
6
7
8
9
10
11
12
# File 'lib/serel/request.rb', line 3

def initialize(type, scoping, qty)
  @type = type
  @scope = scoping.dup
  @site = @scope.delete :site
  @api_key = @scope.delete :api_key
  raise Serel::NoAPIKeyError, 'You must configure Serel with an API key before you can make requests' if @api_key == nil
  @method = @scope.delete :url
  @network = @scope.delete :network
  @qty = qty
end

Instance Method Details

#build_query_stringObject



20
21
22
23
24
25
26
27
# File 'lib/serel/request.rb', line 20

def build_query_string
  query_hash = @scope
  unless @network
    query_hash[:site] = @site
  end
  query_hash[:key] = @api_key
  @query_string = query_hash.map { |k,v| "#{CGI::escape(k.to_s)}=#{CGI::escape(v.to_s)}"}.join('&')
end

#build_request_pathObject



29
30
31
# File 'lib/serel/request.rb', line 29

def build_request_path
  @path = "/2.0/#{@method}?#{@query_string}"
end

#executeObject



14
15
16
17
18
# File 'lib/serel/request.rb', line 14

def execute
  build_query_string
  build_request_path
  make_request
end

#make_requestObject



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
# File 'lib/serel/request.rb', line 33

def make_request
  Serel::Base.logger.info "Making request to #{@path}"
  http = Net::HTTP.new('api.stackexchange.com', 443)
  http.use_ssl = true
  response = http.get(@path)
  body = JSON.parse(response.body)

  result = Serel::Response.new

  # Set the values of the response wrapper attributes
  %w(backoff error_id error_message error_name has_more page page_size quota_max quota_remaining total type).each do |attr|
    result.send("#{attr}=", body[attr])
  end

  # Set some response values we know about but SE might not send back
  result.page ||= (@scope[:page] || 1)
  result.page_size ||= (@scope[:pagesize] || 30)

  # If any items were returned, iterate over the results and populate the response
  if body["items"]
    body["items"].each do |item|
      result << Serel.const_get(@type.to_s.classify).new(item)
    end
  end

  if (@qty == :plural) || (result.length > 1)
    result
  else
    result.pop
  end
end