views:

522

answers:

3

I have my json serialization working fine

render :json => "#{current_object.serialize(:json, :attributes => [:id, :name])}

But I also want to add further data to the json before it gets set back to the client. Mainly the auth_token.

Googled around like crazy but I can not find what option serialize will take to allow me to append/merge my other data into the JSON.

Hopting to find something like this...

current_object.serialize(:json, :attriubtes => [:id, name], :magic_option => {:form_authenticity_token => "#{form_authenticity_token}"})
A: 

Hacked it in and moving on...

current_object.serialize(:json, :attributes => [:id, :name]).gsub(/\}$/, ", \"form_authenticity_token\": \"#{form_authenticity_token}\"}")
+3  A: 

You want the :methods key, which works like :attributes, but will include the results of the methods given. In your case:

current_object.to_json(
  :attributes => [:id, :name],
  :methods => [:form_authenticity_token]
)
Sam C
Sorry I guess I could have explained things a little better. The extra data I'm looking to append (form_aithenticity_token) is not a function of the ActiveRecord model. Also to note is that calling #to_json leaves out the root node. {model_name: {...}}
A: 

For what it's worth, in a recent Rails I hacked together what you want like this:

sr = ActiveRecord::Serialization::Serializer.new(your_object, some_serialization_options).serializable_record
sr['extra'] = my_extra_calculation(some_parameters)
format.json { render :json => sr }

Where your_object is what you want to serialize, some_serialization_options are your standard :include, :only, etc parameters, and my_extra_calculation is whatever you want to do to set the value.

Jimmy