Rails宝典之第六十四式: 自定义Helper模块

本文介绍如何在Rails应用中创建和使用自定义Helper模块,实现功能包括价格格式化显示及路径辅助方法等,通过简单配置即可在控制器中全局调用。
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值