In the weekend of BugMash for Rails3. I planned to make a experiment of a showcase using Rails3 and the new released jQuery 1.4. Rails3 in this experiment would act as a back-end service provider using JSON and the UI stuff would be all handled by jQuery. Therefore making a scaffold generating will save my time for just exposing my simple models in the JSON format.
After the generating, the controller code is look like:
def index
  @tasks = Task.all
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @tasks }
  end
end
Actually this is not near from what I need. RESTful methods that handling JSON are enough and html/xml is not needed.
In rails 2.x there are no support in the core framework to change the scaffold template easily.
I anticipated the scaffold generator would become smarter in Rails 3 just like using some options like —type=JSON then the generated result will be changed.
But the magic did not happen. I called for help in IRC #railsbridge and josevalim told me a easy way to customize my own generating template:
Just make a copy of the template at 
rails/railties/lib/generators/rails/scaffold_controller/templates (or it’s github link) to
RAILS_ROOT/lib/templates/rails/scaffold_controller/controller.rb
The code in template is look like
# GET /<%= table_name %>
# GET /<%= table_name %>.xml
def index
  @<%= table_name %> = <%= orm_class.all(class_name) %>
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @<%= table_name %> }
  end
end
I modified it to my own version:
# GET /<%= table_name %>
def index
  @<%= table_name %> = <%= orm_class.all(class_name) %>
  render :json => @<%= table_name %>
end
Then run generating again. Then it comes the controller that I need:
# GET /tasks
def index
  @tasks = Task.all
  render :json => @tasks
end
Easy enough, right?
 
Comments