views:

52

answers:

1

I know you can pass methods the values of which you want to be available to json objects like so:

# user.rb
def name
  first_name + last_name
end

# some controller
render :json => @user.to_json(:methods => :name)

But if I want to massage the value returned from the method a bit (with a text helper say) is there a way to do that? I guess another way to ask this is does #to_json support arbitrary attributes? If not, why not? Has anyone else ran into this before?

+1  A: 

You can use "render :json" to specify arbitrary attributes in the JSON output. Here is an example:

render :json => { :arbitraryAttribute => arbitrary_method_to_call(), :user => @user.to_json }

The above code would generate JSON like the following:

{
    "arbitraryAttribute":"returnValueOfMethodCall",
    "user":{ the result of @user.to_json }
}
mdemmitt
Yes, that's what I've been doing, but it would just be so much nicer to access those attributes as properties on the user object, because that's what they are...
floyd
This doesn't work because `@user.to_json` will return a string. When `render :json` receives that string, the `@user` JSON is escaped.
macek