Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# 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 => ""
define_remote_method :search, :path => '/search.json'
define_remote_method :trends, :path => '/trends/:time_frame.json'
tweets = => {: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 => {: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 << => {:q => "railsconf"})
# 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 = do
include Typhoeus
define_remote_method :foo, :base_uri => "http://localhost:3001", :cache_responses => 60
klass.cache = some_memcached_instance_or_whatever
response =
puts response.body # makes the request
second_response =
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
Remote.put("http://", :body => "this is a request body")"http://localhost:3001/posts.xml",
{:params => {:post => {:author => "paul", :title => "a title", :body => "a body"}}})

This comment has been minimized.

Copy link

commented Sep 15, 2016

Is this gist still accurate? I can't find define_remote_method in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.