Nov 11 2007

Naming Conventions - Ruby and Ruby on Rails

etienne @ 10:02 pm

In  an attempt to see if I can get my "Ruby and Rails Naming Conventions" article back on Google I’ve created this entry to see if it gets listed.

Click on the link to access the actual article Ruby and Rails Naming Conventions

Sorry for the inconvenience.


Nov 09 2007

Ruby and Rails Naming Conventions Article Missing from Search Engines

admin @ 7:44 am

Over the past week or two I’ve noticed traffic to my Blog have dropped dramatically. Upon further investigation I have found that traffic to one of the most popular articles "Ruby and Rails Naming Conventions" have almost dropped to zero.

I’ve checked Google and the other search engines and this article does not appear at all when using the following search terms "rails naming conventions", it use to be one of the top five for quite some time.

I have searched the Internet to try and figure out why my article is no longer listed, but as yet I’ve not found anything that may explain why this has happened. If anyone has any ideas it would be much appreciated if you could let me know. I’m not sure if I can approach Google about this as this seems to be the same for all search engines.

Click on this link to access the actual article Ruby and Rails Naming Conventions 

Oct 28 2007

Ruby and Rails Naming Conventions

etienne @ 10:15 am

I’ve been looking for a consolidated list of all Ruby and Rails naming conventions without too much luck so I’ve started my own. I find I always forget the naming convention especially as I move between projects that use different languages.

Please let me know of any others that I have missed. 

Naming Conventions

Ruby Naming Convention

Ruby uses the first character of the name to help it determine it’s intended use.

Local Variables
Lowercase letter followed by other characters, naming convention states that it is better to use underscores rather than camelBack for multiple word names, e.g. mileage, variable_xyz

Instance Variables
Instance variables are defined using the single "at" sign (@) followed by a name. It is suggested that a lowercase letter should be used after the @, e.g. @colour 

Instance Methods
Method names should start with a lowercase letter, and may be followed by digits, underscores, and letters, e.g. paint, close_the_door

Class Variables
Class variable names start with a double "at" sign (@@) and may be followed by digits, underscores, and letters, e.g. @@colour

Constant names start with an uppercase letter followed by other characters. Constant objects are by convention named using all uppercase letters and underscores between words, e.g. THIS_IS_A_CONSTANT

Class and Module
Class and module names starts with an uppercase letter, by convention they are named using MixedCase, e.g. module Encryption, class MixedCase

Global Variables
Starts with a dollar ($) sign followed by other characters, e.g. $global

Rails Naming Convention

Rails use the same naming convention as Ruby with some additions:

Variables are named where all letters are lowercase and words are separated by underscores, e.g. order_amount, total

Class and Module
Classes and modules use MixedCase and have no underscores, each word starts with a uppercase letter, e.g. InvoiceItem

Database Table
Table names have all lowercase letters and underscores between words, also all table names need to be plural, e.g. invoice_items, orders

The model is named using the class naming convention of unbroken MixedCase and is always the singular of the table name, e.g. table name might be orders, the model name would be Order. Rails will then look for the class definition in a file called order.rb in the /app/models directory. If the model class name has multiple capitalised words, the table name is assumed to have underscores between these words.

Controller class names are pluralized, such that OrdersController would be the controller class for the orders table.  Rails will then look for the class definition in a file called orders_controller.rb in the /app/controllers directory.

Files, Directories and other pluralization
Files are named using lowercase and underscores. Assuming we have an Orders controller then the following other conventions will apply:

  • That there is a helper module named OrdersHelper in the orders_helper.rb found in the app/helpers directory
  • Rails will look for view template files for the controller in the app/views/orders directory
  • Output from this view will then be used in the layout defined in the orders.html.erb in the app/views/layouts directory
  • Test files including order_test.rb will be created in the /test/unit directory, a file will be created in the /test/fixtures directory called orders.yml and finally a file called orders_controller_test.rb will be created in the /test/functional directory

Primary Key
The primary key of a table is assumed to be named id.

Foreign Key
The foreign key is named with the singular version of the target table name with _id appended to it, e.g. order_id in the items table where we have items linked to the orders table.

Many to Many Link Tables
Tables used to join two tables in a many to many relationship is named using the table names they link, with the table names in alphabetical order, for example items_orders.

Automated Record Timestamps
You can get ActiveRecord to automatically update the create and update times of records in a database table. To do this create two specially named columns created_at and updated_at to your table, i.e. t.datetime :created_at and t.datetime :updated_at. If you only want to store the date rather than a date and time, use :created_on and :updated_on.

Naming Convention Summary 

Model Naming Convention

Table: orders
Class: Order
File: /app/models/order.rb
Primary Key: id
Foreign Key: customer_id
Link Tables: items_orders

Controller Naming Convention

Class: OrdersController
File: /app/controllers/orders_controller.rb
Layout: /app/layouts/orders.html.erb

View Naming Convention

Helper: /app/helpers/orders_helper.rb
Helper Module: OrdersHelper
Views: /app/views/orders/… (list.html.erb for example)

Tests Naming Convention

Unit: /test/unit/order_test.rb
Functional: /test/functional/orders_controller_test.rb
Fixtures: /test/fixtures/orders.yml


Aug 26 2007

Ruby on Rails Class Serialize Problem

etienne @ 6:23 pm

I’ve been chasing my tail for the past day trying to track down a problem I was having in serializing a hash that contained two of my custom classes. I have two custom classes:

class Menu


class Permissions


I then have an ActiveRecord class that stores instances of these two classes in a hash which is then saved to my database.

class Role < ActiveRecord::Base

  serialize :credentials
  self.credentials[:permissions] =
  self.credentials[:menu] =

After saving the record to the database I could inspect the field and all the YAML code was present and accounted for, the problem was that when I went to retrieve the serialized field, instead of getting back a hash with my two custom classes (i.e. Menu and Permissions) I was getting both objects of class YAML::Object.

After pulling my hair out for some time, I traced into the Rails code and saw that YAML::Load(string) was being called to unserialize the data. I then went to the YAML site and read more about the library which I admit I have limited knowledge about. I figured out that for some reason YAML was not finding my custom class definitions which meant it used YAML::Object. So now it was a matter of finding out how to tell YAML about my classes.

After doing more searching on the net I came across these articles which gave me the information I needed:

I was able to add the following code to my environment.rb which will ensure any ActiveRecord derived classes will be correctly serialized. I also added two require statements to environment.rb to make sure my custom (non ActiveRecord derived) classes where also correctly serialized.

require ‘permissions’
require ‘menu’

YAML.add_domain_type("ActiveRecord,2007", "") do |type, val|
  klass = type.split(’:').last.constantize
  YAML.object_maker(klass, val)

class ActiveRecord::Base
  def to_yaml_type

class ActiveRecord::Base
  def to_yaml_properties

I restarted my server and everything worked !!!


Aug 19 2007

CSS ID and Class usage

etienne @ 8:24 pm

I’ve always been slightly confused about when to use an ID and when to use a Class in my CSS. I’ve done some research which clarified my understanding.

The key thing to understand is that ID’s must be unique on a page and identifies a specific element, so you can only use a specified ID once per page. Classes on the other hand can be used multiple times on a page, if you are going to use a style that will be applied to multiple elements then use a Class.

I start by looking at all the sections and subsections on the page and how they work together. I identify all the unique sections on the page and define these with DIV’s and ID’s. Normally a page would consist of the following main sections:

#container { … }

#header { … }

#content { … }

#left { … }

#right { … }

#footer { … }

I then define all the child elements within each of these sections, so for example if I want the links in the header to be different to those in the content section I can easily do so. One of the main benefits of this approach is that when you look at the CSS file you can easily see why and where each style is being used.

#header a:link, #header a:visited {
color: red;
text-decoration: none;
font-weight: bold;

#content a:link, #content a:visited {
color: blue;
text-decoration: none;
font-weight: normal;

I define any shared look and feel styles using classes which I then use in different sections, In the case of the sidebar I have a left as well as a right sidebar, they have many look and feel things in common so I create a class called "sidebar" which defines the common styles. I share this common class between the left and right sidebar elements.


.sidebar {
width: 170px;
margin: 0;
padding: 0;

.sidebar p {
font-size: 0.6em;
color: #555;
padding-left: 5px;
padding-top: 3px;}

#left {
float: left;

#right {
float: right;


<div id="left" class="sidebar">
   <p>This is the left sidebar</p>
</div> <!– left –>

<div id="right" class="sidebar">
   <p>This is the right sidebar</p>

Another interesting point is that You are able to apply multiple classes to an element by space separating the classes, this allows an element to inherit multiple classes.

<DIV id="left" class="class1 class2 class3">Hello World!</DIV>


Tag: CSS, classes

Aug 19 2007

fieldWithErrors Overrides my CSS Field Classes

etienne @ 6:07 pm

When there are errors on a form, Rails will normally create a <DIV> element with the fieldWithErrors class wrapped around the fields input statement. If you have your own CSS class wrapped around a field this will be overridden by the fieldWithErrors <DIV> which is a pain.

I was searching for a solution when I found this post:

I’d like to say I came up with this, but I actually found it somewhere else.

I have the following inside my environment.rb file:

ActionView::Base.field_error_proc = do |html_tag, instance|
  msg = instance.error_message
  error_style = "background-color: #f2afaf"
  if html_tag =~ /<(input|textarea|select)[^>]+style=/
    style_attribute = html_tag =~ /style=[’"]/
    html_tag.insert(style_attribute + 7, "#{error_style}; ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " style=’#{error_style}’ "

I now get the desired effect when an error occurs, in my case it changes the background color of the field red, you can change it to whatever effect you want without it interfering with your field CSS classes…perfect!

Aug 11 2007

Ruby Classes and Objects, being Self Aware

etienne @ 3:43 pm

I’m currently writing an article on Ruby’s approach to objects, classes and also the use of self. Coming from a C++ background it has taken me sometime to grasp the Ruby way of doing things.

I’m doing it for a number of reasons, I want to enforce in my own mind the things that I have been learning, I find writing them down helps a lot. I also want to use it as a reference in the future as I’m sure I’ll forgot things down the track, also someone else may find it useful.

So look for Part 1 in a few days.