Naming conventions on Ruby & Ruby on Rails

Ruby Naming Conventions

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 Conventions

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

Ruby on Rails Security Guide

Please refer the following for Ruby on Rails best practices on the security. CSRF and XSS are the most important ones:-


1) CSRF –

2) XSS –

3) Protection flags on cookies –

4) Filter parameter logging –

Ruby on Rails Security – Protection Flags on Session Cookies


When an unsuspecting user visits the site, the JavaScript executes, stealing the ‘sessionId’ cookie and sending it to the malicious user. Using the victim’s session ID, the malicious user can hijack the victim’s session and perform actions on their behalf.

Solution and Fix:

Add the ‘HttpOnly’ flag to the Set-Cookie directive for the session ID. When we  tag a cookie with the HttpOnly flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. Of course, this presumes you have:

  1. A modern web browser
  2. A browser that actually implements HttpOnly correctly

Example and Testing:

The following details are extracted from the ‘Live HTTP Headers’

Before setting the ‘HttpOnly’ flag:-

Set-Cookie: sessionId=EUID%3DLTU3Zjg3YTA3OjEzNj

After setting the ‘HttpOnly’ flag:-

Set-Cookie: sessionId=EUID%3DLTU3Zjg3YTA3OjEzNj; HttpOnly

Links for References:-


TaskJungler for maintaining todo list

TaskJungler is a gem available for Ruby. TaskJuggler is a modern and powerful project management tool. Its new approach to project planning and tracking is far superior to the commonly used Gantt chart editing tools. TaskJuggler uses one or more text files to describe a project. The main project should be placed in a file with the .tjp extension. This main project may include other files. Such included files must have file names with a .tji extension.

Steps for doing it :-

1) Install the gem

sudo gem install taskjuggler

2) Create the .tjp file, below is the example code for maintaining a todo list

* This file contains a project skeletton. It is part of the
* TaskJuggler project management tool. You can use this as a basis to
* start you own project file.
project your_project_id “Your Project Title” 2011-11-11-0:00–0500 +4m {
# Set the default time zone for the project. If not specified, UTC
# is used.
timezone “America/New_York”
# Hide the clock time. Only show the date.
timeformat “%Y-%m-%d”
# Use US format for numbers
numberformat “-” “” “,” “.” 1
# Use US financial format for currency values. Don’t show cents.
currencyformat “(” “)” “,” “.” 0
# Pick a day during the project that will be reported as ‘today’ in
# the project reports. If not specified, the current day will be
# used, but this will likely be outside of the project range, so it
# can’t be seen in the reports.
now 2011-12-24
# The currency for all money values is the Euro.
currency “USD”

# You can define multiple scenarios here if you need them.
#scenario plan “Plan” {
# scenario actual “Actual”

# You can define your own attributes for tasks and resources. This
# is handy to capture additonal information about the project that
# is not directly impacting the project schedule but you like to
# keep in one place.
#extend task {
# reference spec “Link to Wiki page”
#extend resource {
# text Phone “Phone”

copyright “Claim your rights here”

# If you have any text block that you need multiple times to describe
# your project, you should define a macro for it. Macros can even have
# variable segments that you can set upon calling the macro.
# macro Task [
# task “A ${1} task” {
# }
# ]
# Can be called as
# ${Task “big”}
# to generate
# task “A big task” {
# }

# You can attach flags to accounts, resources and tasks. These can be
# used to filter out subsets of them during reporting.
flags important, hidden

# If you want to do budget planning for you project, you need to
# define some accounts.
account cost “Project Cost” {
account dev “Development”
account doc “Documentation”
account rev “Customer Payments”

# The Profit&Loss analysis should be rev – cost accounts.
balance cost rev

# Define you public holidays here.
vacation “New Year’s Day” 2012-01-02
vacation “Birthday of Martin Luther King, Jr.” 2012-01-16
vacation “Washington’s Birthday” 2012-02-20
vacation “Memorial Day” 2012-05-28
vacation “Independence Day” 2012-07-04
vacation “Labor Day” 2012-09-03
vacation “Columbus Day” 2012-10-08
vacation “Veterans Day” 2012-11-12
vacation “Thanksgiving Day” 2012-11-22
vacation “Christmas Day” 2012-12-25

# The daily default rate of all resources. This can be overridden for each
# resource. We specify this, so that we can do a good calculation of
# the costs of the project.
rate 400.0

# This is a set of example resources.
resource r1 “Resource 1”
resource t1 “Team 1” {
managers r1
resource r2 “Resource 2”
resource r3 “Resource 3”

# This is a resource that does not do any work.
resource s1 “System 1” {
efficiency 0.0
rate 600.0

task project “Project” {
task wp1 “Workpackage 1” {
task t1 “Task 1”
task t2 “Task 2”
task wp2 “Work package 2” {
depends !wp1
task t1 “Task 1”
task t2 “Task 2”
task deliveries “Deliveries” {
task “Item 1” {
depends !!wp1
task “Item 2” {
depends !!wp2

# Now the project has been specified completely. Stopping here would
# result in a valid TaskJuggler file that could be processed and
# scheduled. But no reports would be generated to visualize the
# results.

navigator navbar {
hidereport 0

macro TaskTip [
tooltip istask() -8<-
”’Start: ”’ <-query attribute=’start’->
”’End: ”’ <-query attribute=’end’->

<-query attribute=’resources’->
”’Precursors: ”’

<-query attribute=’precursors’->
”’Followers: ”’

<-query attribute=’followers’->

textreport frame “” {
header -8<-
== TaskJuggler Project Template ==
<[navigator id=”navbar”]>
footer “—-“
textreport index “Overview” {
formats html
center ‘<[report id=”overview”]>’

textreport “Status” {
formats html
center -8<-
<[report id=”status.dashboard”]>
<[report id=”status.completed”]>
<[report id=”status.ongoing”]>
<[report id=”status.future”]>

textreport wps “Work packages” {
textreport wp1 “Work package 1” {
formats html
center ‘<[report id=”wp1″]>’

textreport wp2 “Work package 2” {
formats html
center ‘<[report id=”wp2″]>’

textreport “Deliveries” {
formats html
center ‘<[report id=”deliveries”]>’

textreport “ContactList” {
formats html
title “Contact List”
center ‘<[report id=”contactList”]>’
textreport “ResourceGraph” {
formats html
title “Resource Graph”
center ‘<[report id=”resourceGraph”]>’

# A traditional Gantt chart with a project overview.
taskreport overview “” {
header -8<-
=== Project Overview ===

The project is structured into 2 work packages.

# Specification
# <-reportlink id=’frame.wps.wp1′->
# <-reportlink id=’frame.wps.wp2′->
# Testing

=== Original Project Plan ===
columns bsi { title ‘WBS’ },
name, start, end, effort, cost,
revenue, chart { ${TaskTip} }
# For this report we like to have the abbreviated weekday in front
# of the date. %a is the tag for this.
timeformat “%a %Y-%m-%d”
loadunit days
hideresource 1
balance cost rev
caption ‘All effort values are in man days.’

footer -8<-
=== Staffing ===

All project phases are properly staffed. See [[ResourceGraph]] for
detailed resource allocations.

=== Current Status ===

Some blurb about the current situation.

# Macro to set the background color of a cell according to the alert
# level of the task.
macro AlertColor [
cellcolor plan.alert = 0 “#00D000” # green
cellcolor plan.alert = 1 “#D0D000” # yellow
cellcolor plan.alert = 2 “#D00000” # red

taskreport status “” {
columns bsi { width 50 title ‘WBS’ }, name { width 150 },
start { width 100 }, end { width 100 },
effort { width 100 },
alert { tooltip plan.journal
!= ” “<-query attribute=’journal’->” width 150 },
status { width 150 }

taskreport dashboard “” {
headline “Project Dashboard (<-query attribute=’now’->)”
columns name { title “Task” ${AlertColor} width 200},
resources { width 200 ${AlertColor}
listtype bullets
listitem “<-query attribute=’name’->”
start ${projectstart} end ${projectend} },
alerttrend { title “Trend” ${AlertColor} width 50 },
journal { width 350 ${AlertColor} }
journalmode status_up
journalattributes headline, author, date, summary, details
hidetask ~hasalert(0)
sorttasks alert.down, plan.end.up
period %{${now} – 1w} +1w
taskreport completed “” {
headline “Already completed tasks”
hidetask ~(plan.end <= ${now})
taskreport ongoing “” {
headline “Ongoing tasks”
hidetask ~((plan.start <= ${now}) & (plan.end > ${now}))
taskreport future “” {
headline “Future tasks”
hidetask ~(plan.start > ${now})

# A list of tasks showing the resources assigned to each task.
taskreport wp1 “” {
headline “Work package 1 – Resource Allocation Report”
columns bsi { title ‘WBS’ }, name, start, end, effort { title “Work” },
duration, chart { ${TaskTip} scale day width 500 }
timeformat “%Y-%m-%d”
hideresource ~(isleaf() & isleaf_())
sortresources name.up
taskroot project.wp1
# A list of tasks showing the resources assigned to each task.
taskreport wp2 “” {
headline “Work package 2 – Resource Allocation Report”
columns bsi { title ‘WBS’ }, name, start, end, effort { title “Work” },
duration, chart { ${TaskTip} scale day width 500 }
timeformat “%Y-%m-%d”
hideresource ~(isleaf() & isleaf_())
sortresources name.up
taskroot project.wp2

# A list of all tasks with the percentage completed for each task
taskreport deliveries “” {
headline “Project Deliverables”
columns bsi { title ‘WBS’ }, name, start, end, note { width 150 }, complete,
chart { ${TaskTip} }
taskroot project.deliveries
hideresource 1
# A list of all employees with their contact details.
resourcereport contactList “” {
headline “Contact list and duty plan”
columns name,
email { celltext 1 “[mailto:<-email-> <-email->]” },
managers { title “Manager” },
chart { scale day }
hideresource ~isleaf()
sortresources name.up
hidetask 1

# A graph showing resource allocation. It identifies whether each
# resource is under- or over-allocated for.
resourcereport resourceGraph “” {
headline “Resource Allocation Graph”
columns no, name, effort, rate, weekly { ${TaskTip} }
loadunit shortauto
# We only like to show leaf tasks for leaf resources.
hidetask ~(isleaf() & isleaf_())
sorttasks plan.start.up

3) Execute the file  using the below command

tj3 filename.tjp

The HTML files will be created in the folder you execute the above command with the Todo list details. This can be carried out in any folders, it’s not necessary that this has to be done inside the rails application folder.

For more examples,