Pass method chains to to_json
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?
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 }
}
精彩评论