诗歌rails 之自定义Helper模块

关键字: Rails Helper
Rails默认为每个controller指定一个helper,所有的helper都放在app/helpers目录下
但是有些Helper我们希望是全局共享的,一般我们将这些Helper方法都扔在ApplicationHelper模块里
其实我们可以在app/helpers目录下建立我们自定义的Helper模块,如formatting_helper、path_helper等
ruby代码
  1. # formatting_helper.rb  
  2. module FormattingHelper  
  3.   def free_when_zero(price)  
  4.     price.zero? ? "FREE" : number_to_currency(price)  
  5.   end  
  6.   
  7.   def yes_no(bool)  
  8.     bool? 'Yes' : 'No'  
  9.   end  
  10. end  
  11.   
  12. # path_helper.rb  
  13. module PathHelper  
  14.   def articles_path_for_article(article)  
  15.     if article.tip?  
  16.       tips_articles_path  
  17.     else  
  18.       news_articles_path  
  19.     end  
  20.   end  
  21.   
  22.   def product_path(product)  
  23.     if product.kind_of? Book  
  24.       book_path(product)  
  25.     else  
  26.       movie_path(product)  
  27.     end  
  28.   end  
  29. end  
要想使用这些Helper,我们只需修改ApplicationController即可
ruby代码
  1. class ApplicationController < ActionController::Base  
  2.   helper :formatting, :path  
  3. end  
或者直接使用helper :all来使用所有的Helper
posted @ 2009-07-10 11:31  麦飞  阅读(540)  评论(0编辑  收藏  举报