How does Rails know to use “as_json” in a Class

I'm reading this Railscast:

Mid-way down the page, Ryan says

The as_json method is triggered behind the scenes by the render_json call in the controller.

but no more explanation is given. I'm trying to have this class respond with CSV as well, but def as_csv in the class and format.csv { render :csv => in the calling controller does nothing.

So, somehow the class knows when it was initialized by render :json, but I can't figure out how to make it know it was initialized by render :csv. Can someone explain this?


If you pass an object to render :json, the as_json method is called on that object to retrieve a JSON representation of that object. You can overwrite this method so that it returns whatever you want.

This only works specifically for JSON, it's not a general rule that can be applied to all formats. If you'd like to render a CSV representation of some object, you can do it easily enough by using something like:

format.csv do
  render :text => object.as_csv

and then implementing the as_csv method in the class.

Need Your Help

Merge a Hash and an Array in Ruby to form a Hash and add some string to the Array values to be seen in final Hash

ruby-on-rails ruby arrays hash puppet

Need to form a hash with values supplied from a User as a hash and an array ... The end hash should have the array items as keys and some extra strings added to them to make an acceptable hash that...

AngularJS - Unit testing service with value dependency injection

unit-testing angularjs angularjs-service

I am currently experimenting with AngularJS. I have created a simple service, which is initialized from some distant data. The url is passed as an application value.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.