Wednesday, May 13, 2009

Rails Coding Standards

by Sandip Ransing 1 comments

IN ESSENCE: ALL CODE SHOULD BE READABLE!

# DO NOT OPTIMISE for performance - OPTIMISE FOR CLARITY OF CODE

# STYLE: use 2 spaces for indent (not tabs)

# STYLE: Line up hash arrows for readability

# STYLE: put spaces around => hash arrows

# STYLE: put spaces after ',' in method params - but none between method names and '('

# VIEWS: use HAML for views

# VIEWS: break up the structure with white space to help readability - VERTICALLY TOO!

# VIEWS STYLE: Rely on structure of page, without having to insert messages or new components...

# LOGIC: Rails Models should be as heavy as in logic and controllers should be lightweight as much as .

* Example: Effect to visually highlight then drop out an existing element rather than flash a message

* Example: Highlight newly added row rather than a message about it

# AVOID logic in views - they should be simple

# Views indentation should be well formatted.
not like this

<% for joke in @jokes %>
<div class="joke">
<p>
<%= h(truncate(joke.joketext, 20)) %>
<%= link_to 'Read this joke', {:action => 'show_joke', :id => joke} %>
</p>
<p class="author>
by <%= h(joke.author.full_name) %></p>
</div>
<% end %>


* put html generating logic into helpers

* instead of inline ruby logic, add to models (filtering, checking)

# NEVER use ActiveRecord models in migrations unless you re-define them within the migration

* ...otherwise the migration fails when you later remove/rename the AR class

* BETTER SOLUTION: use bootstrapping until deployed!!!

# AJAX only for sub-components of an object, and avoid over-use




CONTROLLER CODING STANDARDS


1. Before filter should be added at the top of controller.

2. Before filter implementation should be immediate after filter declaration

3. Standard rails actions

4. Own custom actions

5. Inter-related actions should be clubbed together.

6. please, try to use of protected, private methods and they should be declared at the bottom of page in order.

7. Controller Actions should be like -
use 2 spaces for indent (not tabs)

def self.published_jokes
find(:all, :conditions => "published = 1")
end


MODEL CODING STANDARDS


#======= HEADER SECTION=========


# SCHEMA INFORMATION WILL BE HERE
# REQUIRE FILES WILL GO HERE


class Model < ActiveRecord::Base

#======== TOP ===================

# LIBRARY OR INCLUDE METHODS
# MODEL RELATIONSHIPS
# VIRTUAL ATTRIBUTES
# ACTIVE RECORD VALIDATIONS

#======== MIDDLE ===============
# CUSTOM VALIDATIONS
# PUBLIC METHODS

#======== BASE ==================
# PROTECTED METHODS
# PRIVATE METHODS

end

Cheers !!!
Sandip

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter