User Tools

Site Tools


coding:rails

Rails

before coding

style guide

rails style guide
SOLID OO-Coding principles


Short style guide summary:

  • Unordered List Item

Model

Moving db searches in the model (Railscast nr. 4)

def self.find_incomplete
  find_all_by_complete(false, :order => 'created_at DESC')
end


Iterate over a collection of active record objects

# bad
Person.all.each do |person|
  person.do_awesome_stuff
end
 
Person.where('age > 21').each do |person|
  person.party_all_night!
end
 
# good
Person.find_each do |person|
  person.do_awesome_stuff
end
 
Person.where('age > 21').find_each do |person|
  person.party_all_night!
end




Views

Layouts

Global layout: application.html.exstension

Controller layout options
for the whole controller: controllername.html.extension

Multiple controllers

layout :user_layout #this method returns a string which layout to use
#or
layout "some_layout"
 
 
private
 
def user_layout
  if current_user.admin?
    "admin"
  else
    "application"
  end
end


Layout per controller method

render layout: 'projects'
render layout: false #renders no layout



Layouts and content_for (Railscast nr.8)
If you want the layout to do something different depending on which template is being rendered.

#in the "projects/index.html.erb"
 
<% content_for :head do %>
  <%= stylesheet_link_tag 'projects' %>
<% end %>
 
#in the "layouts/application.html.erb"
 
<head>
  <title>Todo List</title>
  <%= stylesheet_link_tag 'application' %>
  <%= yield :head %>
</head>



Controller

Instance variable caching (Railscast nr. 1)

def current_user
  @current_user ||= User.find(session[:user_id])
end



Dynamic find_by methods (Railscast nr. 2)

def incomplete
  @tasks = Task.find_all_by_complete(false)
end
 
def last_incomplete
  @task = Task.find_by_complete(false, :order => 'created_at DESC')
end



Find through association - shortcut (Railscast nr. 3)

def show
  @project = Project.find(params[:id])
  @tasks = @project.tasks.find_all_by_complete(false)
end



Seeds

Seed file with nested attributes

seed Ledger::Account, { code: '6510' }, {
  kind: 'expenses',
  name: 'Telefon, Internet',
  editable: true,
  parent: Ledger::Account.find_by_code('65'),
  distributions_attributes: [
    { factor: 40, to_ledger: ks_ber },
    { factor: 40, to_ledger: ks_han },
    { factor: 20, to_ledger: ks_it },
  ]
}

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 193 bytes) in /home_p2/d/o/domidesign.ch/htdocs/domicode.com/wiki/lib/plugins/authplain/auth.php on line 327