I'm a hacker and an early stage investor interested in solving common problems in the simplest way possible.
I'm also the creator of Sociaholic.com - A better way to post tweets to your facebook
Search
Tags
- ruby (5)
- metaprogramming (3)
- facts (2)
- interview (2)
- startups (2)
- 37signals (1)
- active record (1)
- api (1)
- bubble sort (1)
- client (1)
- View all 44 tags
- clojure (1)
- comparison (1)
- db2 (1)
- erlang (1)
- facebook (1)
- fun (1)
- functional programming (1)
- funding (1)
- ibm (1)
- ideatin (1)
- infographic (1)
- jason fried (1)
- java (1)
- jruby (1)
- lean startup (1)
- mainframe (1)
- market report (1)
- meta (1)
- mvp (1)
- paul graham (1)
- real-time (1)
- scala (1)
- sociaholic (1)
- social media (1)
- software development (1)
- sort (1)
- starling (1)
- star trek (1)
- steve jobs (1)
- twitter (1)
- venture (1)
- video (1)
- wrapper (1)
- y combinator (1)
Powerful Twitter API Wrapper in less than 50 lines using Ruby Metaprogramming
I've been long fascinated about active record dynamic finders (find_by_) and wanted to write some thing similarly elegant, this twitter client uses ruby metaprogramming to dynamically generate objects and methods and adds simpler and easy to user methods for Twitter REST API
For. e.g., the REST method 'user/show' at http://api.twitter.com/1/users/lookup.json can be invoked simply by calling Twitter.new("user","pass").user.show(:screen_name => "gregosuri")
Some explanation of the code:
The program is constructed very similarly to active record dynamic finders, at the core it overrides object's method_missing and dynamically constructs the missing methods, Jay Fields has an excellent blog post that explains this technique.
For e.g., in client.statuses.show(:id=>'1234') the client object (Twitter instance) does not have statuses object during initialization, when this is called, it invokes the method_missing of Twitter class, and since this method(statuses) does not have any arguments or ends with post/get, method_missing will return 'self', i.e., in our case the statuses object. The Proxy is used to buffer the methods, this is useful to construct the URL for later use.
Now, 'show' method is called on 'statuses', since this has arguments it get processed by doing a HTTP GET to Twitter API. Once we have response from the server, an instance of TwitterResponse is created, the construct method accepts a hash/array and converts them into attributes and methods by using object.instance_variable_set and object.send in the constructor
Hope this helps, please follow me on twitter and/or subscribe to this blog.

2 Comments