摘自 https://dzone.com/articles/9-best-practices-to-follow-while-coding-in-rails-1
- Caching With Instance Variable
# Bad Practice
class Project < ActiveRecord::Base
belongs_to :creator, :class_name => “User”
def company
creator.company
end
end
# Good Practice
class Project < ActiveRecord::Base
belongs_to :creator, :class_name => “User”
def company
@company ||= creator.company
end
end
- Use Local Variables in Place of Instance Variables in Partials
# Bad Practice
<%= render :partial => 'header' %>
# Good Practice
<%= render :partial => 'header', :locals => {:project => @project}%>
- Prevent SQL Injection
# Bad Practice
User .where(“name = #{params[:name]}“)
# Good Practice
User.where(“name = ?”, params[:name])
User.where(:name => params[:name]
- Avoid the n+1 Problem
# Bad Practice
@users = User.limit(50)
# Good Practice
@users = User.includes(:house).limit(50)
- Follow The Law of Demeter
# Bad Practice
class Project < ActiveRecord::Base
belongs_to :creator
end
<%= @project.creator.name %>
<%= @project.creator.company %>
# Good Practice
class Project > ActiveRecord::Base
belongs_to :creator
delegate :name, :company, :to => :creator, :prefix => true
end
<%= @project.creator_name %>
<%= @project.creator_company %>
- Declare Instance Variables Inside the Action
# Bad Practice
before_filter :get_project
def show
@tasks = @project.tasks
end
private
def get_project
@project = Project.find(params[:id])
end
# Good Practice(有疑惑,我们都是用上面的 XD)
def show
@project = get_project
@tasks = @project.tasks
end
private
def get_project
Project.find(params[:id])
end
- Use Lambda in Scopes
# Bad Practice
scope :recent, where('starting_date > ?', 1.day.ago)
=>
where('starting_date > ?', '02-10-2013 20:00')
where('starting_date > ?', '02-10-2013 20:00')
# Good Practice
scope :recent, lambda{ where('starting_date > ?', 1.day.ago)}
=>
where('starting_date > ?', '02-10-2013 20:00')
where('starting_date > ?', '03-10-2013 21:23')
- Use ? At the End of Method Name If It Is Returning Boolean Value
# Bad Practice
def exist
end
# Good Practice
def exist?
end
- Make Helper Methods for Views
# Bad Practice
<%= f.select( :category, ['Australia', 'Belgium', 'Canada', 'China', 'India', 'Malaysia', 'Switzerland'].collect{|country| [country, country]}) %>
# Good Practice
<%= f.select( :category, country_names.collect{|country| [country, country]}) %>
def country_names
['Australia', 'Belgium', 'Canada', 'China', 'India', 'Malaysia', 'Switzerland']
end
# Bad Practice
<% case @filter %>
<% when 'inbox' %>
<%= render 'inbox'%>
<% when 'sent' %>
<%= render 'sent' %>
<% when 'draft' %>
<%= render 'draft' %>
<% when 'trash'%>
<%= render 'trash' %>
<% end %>
# Good Practice
<%= render filter_templates(@filter) %>
def filter_templates(filter)
case filter
when 'inbox'
render 'inbox'
when 'sent'
render 'sent'
when 'draft'
render 'draft'
when 'trash'
render 'trash'
end
end