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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值