Wednesday, May 21, 2008

Rails Development Tips or Hints part 1

  • Store sessions in the database (or at least not on disk, which is the default).
  • Use a custom configuration file for passwords and API keys instead of storing them in your Subversion repository. I use YAML and mirror the style of database.yml.
  • Use constants where needed. Instead of repeating strings like the address of your customer service reply email, set it once in a constant (in environment.rb or the appropriate environment file) and use that throughout your application.
  • Keep time in UTC. A no brainer, and easy to do.
  • Don’t loop through ActiveRecord models inside other models. Use eager loading if you need to work with multiple associated models. Better yet, write a custom SQL query and let the database do the work for you.
  • Beware of binary fields. By default, all fields are returned with queries, including the full contents of any binary fields. Use :select to pull out only the fields you need.
  • Write tables to cache data for reports that span months and years. It’s much faster than re-generating a year’s worth of reports every time a page is loaded.
  • Create a table with a list of country names. By default, Rails uses strings for selects and lists of countries, which doesn’t work well for reporting or database consistency between models.
  • Avoid bloated controllers. Instead of piling actions into a controller, limit yourself to 10 actions per controller, then rethink your design.
  • Keep your controllers and views skinny. In general, most of your code should be in your models, not your controllers or views.
  • Don’t store objects in the session. Use integers or short strings if necessary, then pull the appropriate object out of the database for the duration of a single request.
  • Avoid heavy response processing. Can you mark a record as needing to be processed, then use a cron job or a messaging server to do the long-running work? BackgroundRB is also an option. (I use this technique for filtering SPAM comments on this blog).
  • Use ar_mailer to queue bulk emails instead of sending them during the Rails response cycle.
  • Monitor your servers with the exception_notification plugin, munin, monit, or other tools.
  • Don’t cut costs on hardware. You’ll quickly lose the money you thought you were saving if your developers have to spend even one day a month on unexpected server maintenance due to poor backups or cheap hardware.
  • Test-drive your development.

1 comment:

Unknown said...

This topic was your advantage among other blogs out there. This blog contains and provide definitely unique ideas and information. Hire Android Developers