Last active
January 5, 2016 14:50
-
-
Save nateberkopec/882a11e8d363803fd5a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
require 'open-uri' | |
require 'active_model' | |
require 'active_support' | |
require 'active_support/core_ext' | |
class Market | |
include ActiveModel::Model | |
ATTRIBUTES = [:id, :schedule, :address, :google_link] | |
attr_accessor :id, :schedule, :address, :google_link | |
end | |
class MarketGateway | |
REMOTE_URL = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/" | |
DEFAULT_LIST_SIZE = 5 | |
attr_accessor :zip_code, :markets | |
def initialize(opts = {}) | |
self.zip_code = opts[:zip_code] | |
end | |
def fetch!(opts = {}) | |
opts[:size] ||= DEFAULT_LIST_SIZE | |
market_list = JSON.load open("#{REMOTE_URL}zipSearch?zip=#{zip_code}") | |
market_ids = market_list["results"].take(opts[:size]).map { |m| m['id'] } | |
self.markets = market_ids.map { |id| fetch_market(id) } | |
end | |
private | |
def fetch_market(id) | |
response = JSON.load open("#{REMOTE_URL}mktDetail?id=#{id}") | |
market_from_json(response["marketdetails"]) | |
end | |
def market_from_json(json) | |
json = json.dup | |
json.deep_transform_keys!(&:underscore) | |
json.select! { |k, _v| Market::ATTRIBUTES.include? k } | |
Market.new(json) | |
end | |
end | |
markets = MarketGateway.new(zip_code: 11237).fetch! | |
# TODO: this code executes 6 network requests in serial order, which is guaranteed | |
# to slow a controller response to a standstill. MarketGateway.fetch! should at least | |
# fetch the individual markets in parallel with something like Typhoeus. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment