Rails默认为每个controller指定一个helper,所有的helper都放在app/helpers目录下
但是有些Helper我们希望是全局共享的,一般我们将这些Helper方法都扔在ApplicationHelper模块里
其实我们可以在app/helpers目录下建立我们自定义的Helper模块,如formatting_helper、path_helper等
[code]
# 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
[/code]
要想使用这些Helper,我们只需修改ApplicationController即可
[code]
class ApplicationController < ActionController::Base
helper :formatting, :path
end
[/code]
或者直接使用[b]helper :all[/b]来使用所有的Helper
但是有些Helper我们希望是全局共享的,一般我们将这些Helper方法都扔在ApplicationHelper模块里
其实我们可以在app/helpers目录下建立我们自定义的Helper模块,如formatting_helper、path_helper等
[code]
# 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
[/code]
要想使用这些Helper,我们只需修改ApplicationController即可
[code]
class ApplicationController < ActionController::Base
helper :formatting, :path
end
[/code]
或者直接使用[b]helper :all[/b]来使用所有的Helper
本文介绍如何在Rails应用中创建和使用自定义Helper模块,实现功能包括价格格式化显示及路径辅助方法等,通过简单配置即可在控制器中全局调用。
2424

被折叠的 条评论
为什么被折叠?



