Rails自定義Helper模塊含義講解
Ruby on Rails開發(fā)框架中有許多可以自定義的模塊,這些東西可以幫助我們更加方便的應(yīng)用框架編寫代碼。在這里我們將會(huì)為大家介紹Rails自定義Helper模塊的相關(guān)含義。#t#
Rails默認(rèn)為每個(gè)controller指定一個(gè)Rails自定義Helper模塊,所有的helper都放在app/helpers目錄下 ,但是有些Helper我們希望是全局共享的,一般我們將這些Helper方法都扔在ApplicationHelper模塊里 。其實(shí)我們可以在app/helpers目錄下建立我們自定義的Helper模塊,如formatting_helper、path_helper等
- # formatting_helper.rb
 - module FormattingHelper
 - def free_when_zero(price)
 - price.zero? ? "FREE" :
number_to_currency(price) - end
 - def yes_no(bool)
 - bool? 'Yes' : 'No'
 - end
 - end
 - # path_helper.rb
 - module PathHelper
 - def articles_path_for_article(article)
 - if article.tip?
 - tips_articles_path
 - else
 - news_articles_path
 - end
 - end
 - def product_path(product)
 - if product.kind_of? Book
 - book_path(product)
 - else
 - movie_path(product)
 - end
 - end
 - end
 - # formatting_helper.rb module 
FormattingHelper def free_when_zero(price)
price.zero? ? "FREE" : number_to_currency(price)
end def yes_no(bool) bool? 'Yes' : 'No'
end end # path_helper.rb module PathHelper
def articles_path_for_article(article) if
article.tip? tips_articles_path else news_
articles_path end end def product_path(product)
if product.kind_of? Book book_path(product)
else movie_path(product) end end end 
要想使用這些Rails自定義Helper模塊,我們只需修改ApplicationController即可
- class ApplicationController
 
< ActionController::Base- helper :formatting, :path
 - end
 - class ApplicationController
 
< ActionController::Base helper
:formatting, :path end
或者直接使用Rails自定義Helper模塊 :all來使用所有的Helper















 
 
 






 
 
 
 