Twitter4R v0.2.0: Model API

Written on 8:53:00 AM by S. Potter

For those that are familiar with the ActiveRecord API, the Model API of Twitter4R should feel fairly natural for you. Currently the raw Twitter REST API inherently exposes three types of models:

  • Status
  • User
  • Message
These model classes are available via the Twitter4R classes Twitter::Status, Twitter::User and Twitter::Message respectively. What you will notice on these classes is that they have the familiar find and create class methods that behave almost identically to ActiveRecord::Base subclasses (or models as we call them in Rails applications). There is one difference, due in part to the slightly different way "connections" to the Twitter4R "datasource" is handled. So below is a non-trivial example of using these ActiveRecord style methods:

gem('twitter4r', '>=0.2.0')
require('twitter')

client = Twitter::Client.new(:login => 'mylogin', :password => 'mypassword')
# I want to post a new status to my timeline, which can also be do by:
#  client.status(:post, 'My new status message')
status = Twitter::Status.create(:client => client, :text => 'My new status message')

user = Twitter::User.find('dictionary', client)
message = Twitter::Message.create(:client => client, :recipient => user, :text => 'canadaphile')
What we see here is very similar to ActiveRecord style models, but not quite. In the find method invoked on Twitter::User above we supplied a second argument, which is the client (the client context or "connection") object. We also make sure to pass in a :client key-value pair in each create method called above. Without it an ArgumentError would be raised by each create call. A few notes:
  • Twitter::User does not define a meaningful create method since Twitter doesn't allow the creation of new user account via their REST API
  • Twitter::User model has some class and instance helper methods, which are described more in the RDoc (see link below)
See the v0.2.0 RDoc for Twitter4R and select the examples/model.rb link from the top left frame.

If you enjoyed this post Subscribe to our feed

No Comment

Post a Comment