Force Mechanize to return HTTP Success when condition is met in Ruby


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'rubygems'
  2. require 'uri'
  3. require 'mechanize'
  4. require 'rack/utils'
  5.  
  6. # so you can do `params.inspect` throughout Mechanize
  7. class NilClass; def search(*args); []; end; end
  8.  
  9. Mechanize::Chain::PostConnectHook.class_eval do
  10.  
  11. def handle(ctx, params)
  12. headers = params[:response].to_hash
  13. if headers.has_key?("location")
  14. headers["location"].each do |location|
  15. url = URI.parse(location)
  16. if url.host == "localhost" && url.port == 4567
  17. params[:res_klass] = Net::HTTPSuccess
  18. end
  19. end
  20. end
  21.  
  22. p params.keys
  23. #=> [:res_klass, :uri, :response_body, :referer, :response, :agent, :verb, :redirects, :connection, :params, :request, :headers]
  24. p params[:uri]
  25. #=> #<URI::HTTPS:0x1aa0810 URL:https://somesite.com?key=value>
  26. p params[:response]
  27. #=> #<Net::HTTPFound 302 Found readbody=true>
  28. p params[:response].to_hash
  29. #=> {"location"=>["http://somesite.com"], "expires"=>["Sat, 01 Jan 2000 00:00:00 GMT"], "content-type"=>["text/html; charset=utf-8"], "date"=>["Mon, 16 Aug 2010 04:31:13 GMT"], "content-length"=>["0"], "cache-control"=>["private, no-cache, no-store, must-revalidate"], "x-cnection"=>["close"], "pragma"=>["no-cache"]}
  30.  
  31. super(ctx, params)
  32. end
  33.  
  34. end
  35.  
  36. agent = Mechanize.new
  37. page = agent.get("https://somesite.com")
  38. # ... tons of redirects,
  39. # then finally we find a match in our `handle` method above,
  40. # and reset the `params[:res_klass]` to `Net::HTTPSuccess`.
  41. # that is a hack to say basically,
  42. # "return the page, we found what we want"
  43. location = URI.parse(page.response.to_hash["location"].to_a.first)
  44. params = Rack::Utils.parse_query(location.query)

URL: force-mechanize-to-return-http-success-when-condition-is-met-in-ruby

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.