例子: html
Model和controller.git
def render_order_created_time(order) order.created_at.to_s(:short) end
這樣若是之後全站的訂單時間格式須要改,那麼只要改一處就好了。github
以上狀況能夠用partial提煉。編程
使用 Partial 的原則api
def create @post = current_user.posts.build(params[:post]) @post.save end
class User < ActiveRecord::Base def full_name [first_name, last_name].join(' ') end def full_name=(name) split = name.split(' ', 2) self.first_name = split.first self.last_name = split.last end end
在view中:
#當表格提交時調用了full_name=(XXX)方法,而後獲得了first_name和last_name兩個參數。
<% form_for @user do |f| %>
<%= f.text_field :full_name %>
<% end %>
在controller🀄️:
class UsersController < ApplicationController
def create @user = User.create(params[:user]) end
<% form_for @post do |f| %>
<%= f.text_field :content %>
<%= check_box_tag 'auto_tagging' %>
<% end %>
class PostController < ApplicationController def create @post = Post.new(params[:post]) if params[:auto_tagging] == '1' @post.tags = AsiaSearch.generate_tags(@post.content) else @post.tags = "" end @post.save end end
class Post < ActiveRecord::Base attr_accessor :auto_tagging before_save :generate_taggings private def generate_taggings unless auto_tagging == '1' self.tags = Asia.search(self.content) end end
<% form_for :note, ... do |f| %>
<%= f.text_field :content %>
<%= f.check_box :auto_tagging %>
<% end %>
class PostController < ApplicationController def create @post = Post.new(params[:post]) @post.save end end
class Invoice < ActiveRecord::Base def self.new_by_user(params, user) invoice = self.new(params) invoice.address = user.address invoice.phone = user.phone invoice.vip = ( invoice.amount > 1000 ) if Time.now.day > 15 invoice.delivery_time = Time.now + 2.month else invoice.delivery_time = Time.now + 1.month end return invoice end end
class InvoiceController < ApplicationController def create @invoice = Invoice.new_by_user(params[:invoice], current_user) @invoice.save end end
app/models/concerns
目錄下(相似view的render partial)
app/controllers/concerns
目錄就是拿來放 controller 的 module 檔案
app/models/concerns/has_cellphone.rb
module HasCellphone
def self.included(base) base.validates_presence_of :cellphone base.before_save :parse_cellphone base.extend ClassMethods end def parse_cellphone # do something end module ClassMethods def foobar # do something end end end
或是使用 Rails ActiveSupport::Concern 語法,能夠更簡潔一點:ruby
app/models/concerns/has_cellphone.rbmodule HasCellphone extend ActiveSupport::Concern included do validates_presence_of :cellphone before_save :parse_cellphone end def parse_cellphone # do something end class_methods do def foobar # do something end end end
最後在 model 裏面 include 便可。markdown
class User < ActiveRecord::Base include HasCellphone end
用全寫的: <%= render :partial => "sidebar", :locals => { :post => @post } %>
不要用簡寫:<%= render :partial => "sidebar" %>
當你仍不知足 Rails 的 concerns 機制時,你會須要更多面向對象的知識,在編程語言教程中有介紹到。關於 Rails 的部分推薦如下補充資料:app