Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rendering

Rendering to JSON

WidgetBlueprint.render(widget).to_json

If you’re using Rails, you may omit .to_json when calling render json:

render json: WidgetBlueprint.render(widget)

Ruby’s built-in JSON library is used by default. Alternatively, you can use the built-in MultiJson extension. Or for total control, implement the around_result and call any serializer you like.

Rendering to a Hash

WidgetBlueprint.render(widget).to_hash

Rendering a view

# Render a view
WidgetBlueprint[:extended].render(widget).to_json

# Render a nested view
WidgetBlueprint["extended.price"].render(widget).to_json

# These two both render the default view
WidgetBlueprint.render(widget).to_json
WidgetBlueprint[:default].render(widget).to_json

Passing options

An options hash can be passed to render. Read more about options.

WidgetBlueprint.render(Widget.all, exclude_if_nil: true).to_json

Rendering collections

render will treat any Enumerable, except Hash, as an array of objects:

WidgetBlueprint.render(Widget.all).to_json

If you wish to be explicit you may use render_object and render_collection:

WidgetBlueprint.render_object(widget).to_json

WidgetBlueprint.render_collection(Widget.all).to_json

Whatever you pass to render_collection must respond to map, yielding zero or more serializable objects, and returning an Enumerable with the mapped results.