lib/john_stamos/client.rb in john_stamos-0.0.1 vs lib/john_stamos/client.rb in john_stamos-0.0.2

- old
+ new

@@ -1,5 +1,7 @@ +require 'logger' + class JohnStamos::Client attr_accessor :proxy def initialize(options={}) default_options = { proxy: nil } @@ -21,37 +23,50 @@ def pinner(username) JohnStamos::Pinner.new(self, username) end def page_content(url) - begin - page = mechanize_agent.get(url) - rescue Mechanize::ResponseReadError => e - $stderr.puts "#{e.class}: #{e.message}" - $stderr.puts "An error occured; attempting to force_parse" - page = e.force_parse - end + response = make_request(url) - page + Nokogiri::HTML(response) end def json_content(url, params) - RestClient.proxy = @proxy - response = RestClient.get(url, params: params, accept: :json, "X-Requested-With" => "XMLHttpRequest") + response = make_json_request(url, params) JSON.parse(response) end private - def mechanize_agent - agent = Mechanize.new - agent.user_agent_alias = 'Mac Safari' + def make_request(url, params={}, accept_json=false) + request_headers = build_request_headers(accept_json) - if @proxy - proxy_uri = URI.parse(@proxy) - agent.set_proxy(proxy_uri.hostname, proxy_uri.port) + response = pinterest_connection.get do |req| + req.url url, params + req.headers = request_headers end - agent + response.body + end + + def make_json_request(url, params={}) + make_request(url, params, true) + end + + def build_request_headers(accept_json=false) + headers = {} + + if accept_json + headers['Accept'] = 'application/json' + headers['X-Requested-With'] = 'XMLHttpRequest' + end + headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36' + + headers + end + + def pinterest_connection + pinterest_url = 'http://pinterest.com' + @pinterest_connection ||= @proxy.nil? ? Faraday.new(url: pinterest_url) : Faraday.new(url: pinterest_url, proxy: @proxy) end end \ No newline at end of file