lib/ocar/client.rb in ocar-0.2.0 vs lib/ocar/client.rb in ocar-0.2.1

- old
+ new

@@ -1,53 +1,47 @@ require 'json' require 'typhoeus' module Ocar - extend self - TYPES = ["cartas", "paquetes", "dni", "partidas" ] + TYPES = %w(cartas paquetes dni partidas).freeze $hydra = Typhoeus::Hydra.new - def get_package track_id - requests = setup_request track_id + def get_package(track_id) + requests = setup_request(track_id) run_request get_response requests end private - def setup_request track_id - requests = TYPES.map { |type| - request = Typhoeus::Request.new("http://www.oca.com.ar", + + def setup_request(track_id) + # e.g. http://www.oca.com.ar/?q=package-locator&type=paquetes&number=1808200000001055400 + TYPES.map do |type| + request = Typhoeus::Request.new( + 'http://www.oca.com.ar', method: :get, - params: { q: "package-locator", - type: type, - number: track_id }, - headers: { Accept: "text/html" } + params: { q: 'package-locator', + type: type, number: track_id }, + headers: { + Accept: 'application/json, text/javascript, */*; q=0.01' + } ) $hydra.queue(request) request - } + end end def run_request $hydra.run end - def get_response requests + def get_response(requests) results = [] - responses = requests.map do |request| + requests.map do |request| parsed = JSON.parse request.response.body results << parsed if parsed['success'] == true end - return check_response results - end - - - def check_response results - if results.any? - Ocar::Status.new(results.first) - else - nil - end + results end end