Rails自定义Helper模块含义讲解
创始人
2024-06-16 09:50:33
0

Ruby on Rails开发框架中有许多可以自定义的模块,这些东西可以帮助我们更加方便的应用框架编写代码。在这里我们将会为大家介绍Rails自定义Helper模块的相关含义。#t#

Rails默认为每个controller指定一个Rails自定义Helper模块,所有的helper都放在app/helpers目录下 ,但是有些Helper我们希望是全局共享的,一般我们将这些Helper方法都扔在ApplicationHelper模块里 。其实我们可以在app/helpers目录下建立我们自定义的Helper模块,如formatting_helper、path_helper等

  1. # formatting_helper.rb   
  2. module FormattingHelper   
  3. def free_when_zero(price)   
  4. price.zero? ? "FREE" :
     number_to_currency(price)   
  5. end   
  6. def yes_no(bool)   
  7. bool? 'Yes' : 'No'   
  8. end   
  9. end   
  10. # path_helper.rb   
  11. module PathHelper   
  12. def articles_path_for_article(article)   
  13. if article.tip?   
  14. tips_articles_path   
  15. else   
  16. news_articles_path   
  17. end   
  18. end   
  19. def product_path(product)   
  20. if product.kind_of? Book   
  21. book_path(product)   
  22. else   
  23. movie_path(product)   
  24. end   
  25. end   
  26. end   
  27. # 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即可

  1. class ApplicationController 
    < ActionController::Base   
  2. helper :formatting, :path   
  3. end   
  4. class ApplicationController 
    < ActionController::Base helper 
    :formatting, :path end   

 

或者直接使用Rails自定义Helper模块 :all来使用所有的Helper

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...