Serialization - Rendering documents

The renderer takes your business objects (which can be any ruby objects: POROs, ActiveRecord models, or even plain hashes), along with some optional parameters (include, fields, etc.), and builds the JSON API document.

Plain ruby

When using jsonapi-rb in plain ruby (or from within a framework outside of a controller), you can render a document as follows:

JSONAPI::Serializable::Renderer.render(posts)

You can also pass options to the renderer:

JSONAPI::Serializable::Renderer.render(posts,
                                       include: [:author, comments: [:author]],
                                       fields:  { users: [:name, :email],
                                                  posts: [:title, :content] })

For a comprehensive list of renderer options, see Renderer options.

Ruby on Rails

When using jsonapi-rb with Rails (via the jsonapi-rails gem), rendering is done via the usual render controller method:

render jsonapi: posts

and options are passed as named arguments:

render jsonapi: posts,
       include: [:author, comments: [:author]],
       fields:  { users: [:name, :email],
                  posts: [:title, :content] }

For a comprehensive list of renderer options, see Renderer options.

Hanami

When using jsonapi-rb with Hanami (via the jsonapi-hanami gem), enabling of jsonapi-rb features is opt-in, and is done by including JSONAPI::Hanami::Action in your actions. Rendering is done by setting options directly on the controller action instance. The primary data is set via the self.body setter.

Exposures are available from within the SerializableResource class as instance variables.

Example:

module API::Controllers::Posts
  class Create
    include API::Action
    include JSONAPI::Hanami::Action

    expose :url_helpers

    def call(params)
      # ...
      @url_helpers = routes  # Will be available inside serializable resources.

      self.data = posts
      self.include = [:author, comments: [:author]]
      self.fields  = { users: [:name, :email],
                       posts: [:title, :content] }
    end
  end
end

For a comprehensive list of renderer options, see Renderer options.

Renderer options

The available options are: