Rails自定义Helper模块含义讲解
Ruby on Rails开发框架中有许多可以自定义的模块,这些东西可以帮助我们更加方便的应用框架编写代码。在这里我们将会为大家介绍Rails自定义Helper模块的相关含义。
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即可
相关推荐
wl00 2020-10-28
EricNet 2020-07-05
EricNet 2020-05-27
何志文 2020-05-11
JOO 2020-04-26
happyfreeangel 2020-04-09
Poisedflw 2020-03-23
yangliuhbhd 2020-03-06
Ben的程序员生涯 2013-06-01
chenshuixian 2013-06-01
wes0 2014-05-31
mrice00 2019-12-20
EricNet 2019-12-11
89304896 2019-12-08
lihaoningxia 2013-07-09
userguanguan 2015-03-16