Archive for March 4th, 2008

Customizing ActiveScaffold

Mar 04, 2008 in Ruby, Web Development

At first I was a little skeptical about the ability of ActiveScaffold to really do everything I needed to do, and not involve massive amounts of hacking apart the code. It actually turned out to be fairly easy and offered a great solution for some of the administrative side of HeelsHousing.

First off while not very well documented in my opinion is the ability of rails to have and understand sub controllers, such as the URI “/admin/users” which would be the controller in “app/controllers/admin/users_controller.rb”. To do this just requires some code like this:

app/controllers/admin_controller.rb

class AdminController < ApplicationControllerend

module Admin
end

app/controllers/admin/user_controller.rb

class Admin::UsersController < AdminController

   active_scaffold :user do |config|end

end

Of course the main thing we wanted to do was to style it to match other administrative interfaces we were using. In case you don’t know already the ActiveScaffold team really thought ahead on this one and allows customization at pretty much every level. For sweaping changes that effect style most likely you’re looking at Template Overrides. Since we were looking to have all administrative forms look the same we just had to provide new template in the “app/views/active_scaffold_overrides/” directory. The templates that I found were needed for really doing what I we needed to do to change the look of the forms were the “_form.rhtml”, “_form_association.rhtml”, “_form_association_record.rhtml”, and “_form_attribute.rhtml” templates.

Of course you also often want to change the specifics of how a specific form input is generated for a given column is generated. And for this there’s Form Overrides. These are just little helpers in the helper file for the given controller. So say you want to change the type of input used for your password column on the User form, just add a method called “password\_form \_column” in the “user.helper.rb” file.
But let’s say you want to change all columns that are strings to function in a specific way, like say setting the size and maxlength attributes, well here ya go:

Article.columns.each do |column|
   if column.type == :string
      size = (column.limit > 59) ? 60 : column.limit + 1
      src = <<-end_src
         def #{column.name}_form_column(record, input_name)
            text_field(:record, '#{column.name}', :size => #{size}, :maxlength => #{column.limit}, :name => input_name)
         end
      end_src
      class_eval src, __FILE__, __LINE__
   end
end

Well there’s really lots more I could cover about active scaffold but I’ll let you sophisticats check it out for yourself. The documentation is top notch. All in all a great addition to your Rails toolbox.

Tags: , , , ,