# This is a code example for the Ruby HTTP library Typhoeus # here's an example for twitter search # Including Typhoeus adds http methods like get, put, post, and delete. # What's more interesting though is the stuff to build up what I call # remote_methods. class Twitter include Typhoeus remote_defaults :on_success => lambda {|response| JSON.parse(response.body)}, :on_failure => lambda {|response| puts "error code: #{response.code}"}, :base_uri => "http://search.twitter.com" define_remote_method :search, :path => '/search.json' define_remote_method :trends, :path => '/trends/:time_frame.json' end tweets = Twitter.search(:params => {:q => "railsconf"}) # if you look at the path argument for the :trends method, it has :time_frame. # this tells it to add in a parameter called :time_frame that gets interpolated # and inserted. trends = Twitter.trends(:time_frame => :current) # and then the calls don't actually happen until the first time you # call a method on one of the objects returned from the remote_method puts tweets.keys # it's a hash from parsed JSON # you can also do things like override any of the default parameters Twitter.search(:params => {:q => "hi"}, :on_success => lambda {|response| puts response.body}) # on_success and on_failure lambdas take a response object. # It has four accesssors: code, body, headers, and time # here's and example of memoization twitter_searches = [] 10.times do twitter_searches << Twitter.search(:params => {:q => "railsconf"}) end # this next part will actually make the call. However, it only makes one # http request and parses the response once. The rest are memoized. twitter_searches.each {|s| puts s.keys} # you can also have it cache responses and do gets automatically # here we define a remote method that caches the responses for 60 seconds klass = Class.new do include Typhoeus define_remote_method :foo, :base_uri => "http://localhost:3001", :cache_responses => 60 end klass.cache = some_memcached_instance_or_whatever response = klass.foo puts response.body # makes the request second_response = klass.foo puts response.body # pulls from the cache without making a request # you can also pass timeouts on the define_remote_method or as a parameter # Note that timeouts are in milliseconds. Twitter.trends(:time_frame => :current, :timeout => 2000) # you also get the normal get, put, post, and delete methods class Remote include Typhoeus end Remote.get("http://www.pauldix.net") Remote.put("http://", :body => "this is a request body") Remote.post("http://localhost:3001/posts.xml", {:params => {:post => {:author => "paul", :title => "a title", :body => "a body"}}}) Remote.delete("http://localhost:3001/posts/1")