ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年9月7日 星期一
railscast skill
Refactoring User Name Part 2
# models/user.rb
def full_name
[first_name, middle_initial_with_period, last_name].compact.join(' ')
end
def middle_initial_with_period
"#{middle_initial}." unless middle_initial.blank?
end
Fun with Find Conditions
Task.find(:all, :conditions => ["complete=? and priority=?", false, 3])
Task.find(:all, :conditions => ["complete=? and priority IS ?", false, nil])
Task.find(:all, :conditions => ["complete=? and priority IN (?)", false, [1,3]])
Task.find(:all, :conditions => ["complete=? and priority IN (?)", false, 1..3])
Task.find(:all, :conditions => { :complete => false, :priority => 1 })
Task.find(:all, :conditions => { :complete => false, :priority => nil })
Task.find(:all, :conditions => { :complete => false, :priority => [1,3] })
Task.find(:all, :conditions => { :complete => false, :priority => 1..3 })
Task.find_all_by_priority(1..3)
Multibutton Form
<% if params[:preview_button] %>
<%= textilize @project.description %>
<% end %>
...
<%= submit_tag 'Create' %>
<%= submit_tag 'Preview', :name => 'preview_button' %>
# projects_controller.rb
def create
@project = Project.new(params[:project])
if params[:preview_button] || !@project.save
render :action => 'new'
else
flash[:notice] = "Successfully created project."
redirect_to project_path(@project)
end
end
Refactoring Long Methods
# models/cart.rb
def shipping_price
if total_weight == 0
0.00
elsif total_weight <= 3
8.00
elsif total_weight <= 5
10.00
else
12.00
end
end
def total_weight
@total_weight ||= line_items.to_a.sum(&:weight)
end
# models/line_item.rb
def weight
for_download? ? 0 : product.weight
end
Cleaning Up the View
<% title "Shopping Cart" %>
Product
Qty
Unit Price
Full Price
<%= render :partial => 'line_item', :collection => @cart.line_items %>
Total: <%= number_to_currency @cart.total_price %>
<[tr class="<%= cycle :odd, :even %>"]>
<%=h line_item.product.name %>
<%= line_item.quantity %>
<%= free_when_zero(line_item.unit_price) %>
<%= free_when_zero(line_item.full_price) %>
<[/tr]>
# models/line_item.rb
def full_price
unit_price*quantity
end
# models/cart.rb
def total_price
line_items.to_a.sum(&:full_price)
end
# helpers/carts_helper.rb
def free_when_zero(price)
price.zero? ? "FREE" : number_to_currency(price)
end
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言