selectively include or exclude json root, either will do #383

Closed
garyfoster opened this Issue Jan 3, 2013 · 1 comment

2 participants

@garyfoster

I have an API where there are a few instances where I need different behavior for the root element. I can control this globally with the include_json_root config setting but I can not seem to change this on a single template. Can you tell me if it's possible and how to achieve this in either one or both of the following scenarios? In the 1st scenario, I tried "object @user => :user" but this had no affect.

-------- Scenario 1 --------
Config:
config.include_json_root = false

Template:
object @user
attributes :id, :first_name, :last_name

Output:
{"id": 1, "first_name": "Gary", "last_name": "Foster"}

Desired Output:
{"user":{"id":1,"first_name":"Gary","last_name":"Foster"}}

-------- Scenario 2 --------
Config:
config.include_json_root = true

Template:
object @user
attributes :id, :first_name, :last_name

Output:
{"user":{"id":1,"first_name":"Gary","last_name":"Foster"}}

Desired Output:
{"id": 1, "first_name": "Gary", "last_name": "Foster"}

@nesquena
Owner

Not necessarily ideal but fairly straightforward. Keep the json_root as true and then in the case where you need it to be false you can do:

node do
  partial("users/base", :object => @user)
end

which will render without a root key or even as simple as:

node do
  res = {}
  [:id, :first_name, :last_name].each { |a| res[a] = @user.send(a) }
  res
end

I know it'd be nice to be able to maintain the same template format and just sort of easily toggle between the root and no root at the object level and that might happen one day. For instance something like:

object @user, :root => false

would be cool in the future.

@nesquena nesquena closed this Jan 8, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment