Rails自定义Helper模块含义讲解

开发 开发工具
Rails自定义Helper模块全部被放在app/helpers目录下,如果我们想染一部分Rails自定义Helper模块进行全局共享的话又该如何呢?

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

责任编辑:曹凯 来源: 博客园
相关推荐

2012-05-18 10:52:20

TitaniumAndroid模块自定义View模块

2020-11-19 10:50:43

ImportPython代码

2009-06-30 10:40:25

JSP自定义标签

2009-07-02 15:31:49

JSP标签

2024-02-20 08:01:08

SQL注入器MyBatis数据库

2015-02-12 15:33:43

微信SDK

2010-02-25 16:14:51

Visual Stud

2015-02-12 15:38:26

微信SDK

2024-01-01 13:27:44

pydoc工具代码

2016-11-16 21:55:55

源码分析自定义view androi

2016-12-26 15:25:59

Android自定义View

2011-06-23 10:49:13

Qt 自定义信号

2009-07-06 16:59:26

JSP自定义标签

2013-04-19 10:14:24

2010-09-14 16:47:23

SQL自定义函数

2015-07-22 10:57:36

watchOS图表自定义

2013-06-27 11:10:01

iOS开发自定义UISlider

2021-12-28 15:38:46

Traefik中间件插件

2023-09-06 10:33:40

夜莺监控数据库

2009-12-14 15:30:43

安装Ruby on R
点赞
收藏

51CTO技术栈公众号