Ruby on Rails开发框架中有许多可以自定义的模块,这些东西可以帮助我们更加方便的应用框架编写代码。在这里我们将会为大家介绍Rails自定义Helper模块的相关含义。#t#
Rails默认为每个controller指定一个Rails自定义Helper模块,所有的helper都放在app/helpers目录下 ,但是有些Helper我们希望是全局共享的,一般我们将这些Helper方法都扔在ApplicationHelper模块里 。其实我们可以在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