Class: DonorsChoose::Request

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

Overview

This class provides a wrapper around all of the external interaction we'll be doing. It's kinda important, given we're wrapping an API. ;)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Request

This API operates through making GET requests to an endpoint. It takes a few different parameters to control how the data is acquired. We'll just take those so we can properly construct the request.



22
23
24
# File 'lib/donors_choose/request.rb', line 22

def initialize(params)
  @params = params
end

Class Method Details

.get(params) ⇒ Object

This method is a convenient factory method, and is the easiest way to make a single request and get the data back.



15
16
17
# File 'lib/donors_choose/request.rb', line 15

def self.get(params)
  new(params).process
end

Instance Method Details

#getObject

This method wraps Net::HTTP, basically. We build up our own parameter list, construct our URI, and fetch it.



36
37
38
39
# File 'lib/donors_choose/request.rb', line 36

def get
  base_uri = 'http://api.donorschoose.org/common/json_feed.html'
  Net::HTTP.get(URI(base_uri + "?" + uri_params))
end

#processObject

This method is the main business process of this class: get the data, parse the JSON it returns, grab the proposal list, and then build a list of objects with the data.



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

def process
  data = JSON.parse(get)["proposals"]
  data.collect {|datum| DonorsChoose::Utils::StaticStruct.new(datum)}
end

#uri_paramsObject



41
42
43
44
45
46
47
# File 'lib/donors_choose/request.rb', line 41

def uri_params
  params = @params.dup.collect do |key, value|
    "#{key}=#{CGI.escape(value.to_s)}"
  end
  params << "APIKey=#{DonorsChoose.api_key}"
  params.join("&")
end