2 minutes admin layout with rails and the web-app-theme generator
Many people found out a rails generator inside my web-app-theme project and asked me how to use it. Here an example, starting from scratch with a new rails app that manages music Albums.
rails cool_albums
cd cool_albums
script/generate scaffold Album name:string artist:string date:date
rake db:migrate
After creating the first controller with a scaffold or with your hands, start creating a theme:
script/plugin install git://github.com/gravityblast/web-app-theme.git
script/generate theme application --app_name="My Cool Albums" --theme="drastic-dark"
The first argument (“application”) is the name of the layout that the generator will create (application.html.erb). The –app_name option specifies the name used as page title, and with the –theme specifies which theme to use among all the available themes inside the plugin.
Now remove the default index.html created by rails and the layout created by the scaffold:
rm app/views/layouts/albums.html.erb
rm public/index.html
Add the following line in your routes.rb to set the default page of the application:
map.root :controller => :albums
Start the server
script/server
Ok, the layout has been successfully created, but we need to apply a theme for each one of the views generated by the scaffold
script/generate themed albums album --layout=application --with_will_paginate
With the first 2 arguments I specified the controller path (albums) and the model used (album). The –layout options is used by the themed generator to know where to add the Albums menu link.
Since we want to use will paginate (we set the –with_will_paginate option), we need to change one line in our albums controller from:
@albums = Album.all
to:
@albums = Album.paginate(:per_page => 10, :page => params[:page])
Here a trick to show form error messages inside the auto generated forms, you can add the following lines in your environment.rb:
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
Ok, restart your server and you are done.
Feel free to fork the project from github to improve the generator or to add a new theme.