The api-twister gem is a ruby DSL to define non-trivial APIs.
It works with Rails 2, Rails 3, and without Rails (you will need ActiveSupport, though). It works with ruby 1.9.1 and 1.9.2, and possibly others.
Defining a simple REST API in Rails that returns simple objects is easy. Do it.
However, if you are returning nested objects, want to include methods in your responses, or want to exclude certain attributes, the basic configuration methods can get ugly quickly. Also if you have different serialization options and do not want to use HTTP response codes to describe them (for example, no results were found in a search), things can get ugly. This library hides much of the ugly. It puts knowledge of what attributes, methods, and associations to return in each model class. It allows you to define different named serialization options.
gem install api-twister
Add to your Gemfile:
gem 'api-twister'
Add to your environment.rb:
config.gem 'api-twister'
-
Define your API methods in your models using api_define.
-
Call to_api_json/to_api_xml to serialize your models. These methods use api_hash to build an options hash based on what you defined in your models.
-
Build sample requests/responses for tests.
-
Build real requests/responses for controllers and documentation pages.
class Monkey < ActiveRecord::Base has_many :bananas include ApiTwister define_api do |api| api.methods :behavior, :favorite_number, :status api.association :bananas end api :request, :only => [:name] api :response # default is everything in define_api api :error_response, :only => [:status] def behavior name == 'Mr. Bananas' ? 'Good' : 'Bad' end def favorite_number rand(10) end def status valid? ? 'OK' : 'Error' end end class Banana < ActiveRecord::Base belongs_to :monkey include ApiTwister define_api {|a| a.method :edible} api :request api :response def edible created_at > 10.days.ago ? 'Yes' : 'No' end end
# TODO - more docs
Fork away. Please create a topic branch and write passing tests if you are submitting a pull request.
git clone git://github.com/yourname/api-twister.git cd api-twister bundle install rake test git checkout -b your_fix
Scott Jacobsen
Tee Parham