在Ruby on Rails里面,首先应该明确的一点 —– Helper是view的helper,根据这个原则,在默认实现下,controller是不允许访问helper里面的方法的。当然helper在本质上是一个module,所以要在controller和helper之间共享一些方法的办法还是很多的。因为是双方都拥有的方法,所以就面临一个问题 —— 方法放在那里比较合理?controller还是helper?我阐述一下我的原则:
如果方法中需要引入其他helper方法,那么我们建议该方法放在helper中;否则,可以放在controller中或者写一个公共module。放在controller里面需要注意安全性,因为controller里面public的方法很有可能通过URL加以执行,所以我们建议所有的helper 方法都用private 加以约束。
下面我就详细说一下4中方法。
Helper方法放在controller中,通过ApplicationHelper来实现公用。代码存在一定的安全隐患。
module ApplicationHelper
def method_missing(method, *args, &block)
if ApplicationController.instance_methods.include? method.to_s
controller.send(method, *args, &block)
else
super
end
end
end
Helper方法放在controller中,通过helper_method来实现公用。代码安全。
private
heper_method :login?
def login?
# your logic goes here
end
Helper方法放在Helper中,通过include module_name向controller暴露,代码安全
include FullModuleName
Helper方法放在一个独立的module中,helper和controller通过include这个module来获得公共方法。
include CommonModuleName
关于include module需要注意的是,它不会帮助你去自动解决module依赖性的问题。
----------------------------------------补充----------------------------------------
但是有些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
要想使用这些Helper,我们只需修改ApplicationController即可
- class ApplicationController < ActionController::Base
- helper :formatting, :path
- end
class ApplicationController < ActionController::Base
helper :formatting, :path
end
或者直接使用 helper :all来使用所有的Helper