blueprinter icon indicating copy to clipboard operation
blueprinter copied to clipboard

Can I set `:root` globally?

Open aguynamedben opened this issue 4 years ago • 2 comments

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

aguynamedben avatar Jan 17 '21 19:01 aguynamedben

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
}

aguynamedben avatar Jan 17 '21 19:01 aguynamedben

I would love this as well :)

Frexuz avatar Jul 01 '21 11:07 Frexuz

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.

github-actions[bot] avatar Nov 02 '23 01:11 github-actions[bot]