Can I set `:root` globally?
I'm migrating to Blueprinter from JBuilder. My current API always uses "items" for root. With Blueprinter I know I can use the :root argument while rendering to put my item(s) under a key, but is there any way to set :root globally? I didn't see anything in the configuration code.
Is this a valid feature request? If I implement it would you consider it for merging?
Example:
Blueprinter.configure do |config|
# for all renders, put the object/collection under the "items" key
config.default_root = :items
end
This use case probably only makes sense if the default root value is always an array (...?)
Blueprinter.configure do |config|
# for all renders, put the object/collection under the "items" key
config.default_root = :items
# ensure the value of "items" is always an array, even if an object is
config.default_root_force_array = true
end
Maybe there's a better way to allow customization at the root level, i.e. a block I can customize right before the rendering steps. That might solve this question too.
Blueprinter.configure do |config|
config.before_render do |object_or_collection, hash|
# always put the rendered item under an 'items' key
hash[:items] = hash
# include Kaminari pagination at the root level
if object_or_collection.respond_to?(:limit_value)
hash[:page_size] = object_or_collection.limit_value
end
if object_or_collection.respond_to?(:current_page)
hash[:current_page] = object_or_collection.current_page
end
if object_or_collection.respond_to?(:total_pages)
hash[:last_page] = object_or_collection.total_pages
end
hash
end
end
Usage
organizations = Organization.accessible_by(current_ability).
page(params['page'] || 1).
per(params['page_size'] || 25)
json = OrganizationBlueprint.render(organizations)
render json: json, status: :ok
Output
{
"items": [
{
"uuid": "cb00c77e-d9ee-4abe-8e59-e4d4686af671",
"created_at": "2020-04-22 04:28:18 UTC",
"name": "Command E",
"slug": "command-e",
"updated_at": "2020-04-22 04:28:18 UTC"
},
{
"uuid": "33ea61a2-e7d1-432a-9b78-c156a2c18805",
"created_at": "2020-04-22 04:42:56 UTC",
"name": "Lyft",
"slug": "lyft",
"updated_at": "2020-12-18 05:25:11 UTC"
}
],
"page_size": 25,
"current_page": 1,
"last_page": 1
}
I would love this as well :)
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.