Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Instead of to_xml and as_json, simply implement to_api. Return an unformatted hash. Let the model understand the data. Let the controller understand the format. In Rails, the controller can simply call render :xml => model.to_api or render :json => model.to_api.

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .ruby-version
Octocat-spinner-32 Gemfile
Octocat-spinner-32 README.md
Octocat-spinner-32 Rakefile
Octocat-spinner-32 to_api.gemspec
README.md

Description

A lightweight, format-agnostic API transformation gem.

Synopsis

Models shouldn't know about formats. Controllers shouldn't know what attributes your domain objects have. It should be trivial to serve the same data in multiple formats.

How do I use it?

Implement to_api on your data objects to return a hash with all needed attributes.

class Person
  attr_accessor :first_name, :last_name, :secret

  def to_api
    {:first_name => @first_name, :last_name => @last_name}.to_api
  end
end

class Group
  attr_accessor :name, :description, :people

  def to_api
    {:name => @name, :description => @description, :people => @people}.to_api
  end
end

Now just call your to_api method. You'll get back a hash of arrays, hashes, strings, numbers, and nil. All of these are very easily converted to a format of your choice.

JSON.generate(group.to_api)

If I have to implement to_api, what does the gem do for me?

The gem provides to_api for common Ruby classes, allowing simple conversion to JSON, XML, YAML, etc. Hash and Enumerable transform all their contents, allowing your data objects to simply call to_api on a hash of relevant attributes.

Fixnum, String, DateTime, Symbol, and NilClass are also provided.

What about Ruby on Rails?

If ActiveRecord is present, ActiveRecord::Base#to_api transforms and returns the attributes hash. It also supports an :includes option that mirrors the ActiveRecord finder usage.

person.to_api([{:groups => :members}, :interests])

What if I need support for other common classes?

For most classes, it only takes a couple specs and a few lines of code. Send a pull request; we'd love to take your additions.

Authors

Something went wrong with that request. Please try again.