如何设置url helper方法参数的默认值?
我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1
。 这就是我在routes.rb中所做的:
scope ":lang" do resources :posts end
现在我可以轻松使用url helpers,例如: post_path(post.id, :lang => :en)
。 问题是我想在cookie中使用一个值作为默认语言。 所以我只能写post_path(post.id)
。
有没有办法如何在url helpers中设置参数的默认值? 我找不到url助手的源代码 – 有人能指出我正确的方向吗?
另一种方式:我已经尝试在routes.rb中设置它,但它仅在启动时评估,这对我不起作用:
scope ":lang", :defaults => { :lang => lambda { "en" } } do resources :posts end
这是我的头编码,所以不能保证,但在初始化器中尝试一下:
module MyRoutingStuff alias :original_url_for :url_for def url_for(options = {}) options[:lang] = :en unless options[:lang] # whatever code you want to set your default original_url_for end end ActionDispatch::Routing::UrlFor.send(:include, MyRoutingStuff)
或直的猴子补丁……
module ActionDispatch module Routing module UrlFor alias :original_url_for :url_for def url_for(options = {}) options[:lang] = :en unless options[:lang] # whatever code you want to set your default original_url_for end end end end
url_for的代码位于Rails 3.0.7中的actionpack / lib / routing / url_for.rb中
Ryan Bates在今天的railscast中报道了这一点: http: //railscasts.com/episodes/138-i18n-revised
你可以在这里找到url_for的来源: http : //api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html
您将看到它将给定的选项与url_options合并,而url_options又调用default_url_options 。
将以下内容作为私有方法添加到application_controller.rb中,您应该进行设置。
def locale_from_cookie # retrieve the locale end def default_url_options(options = {}) {:lang => locale_from_cookie} end
上面的doterr几乎得到了它。 那个版本的default_url_options对其他人不会很好。 你想要增加而不是传入的clobber选项:
def locale_from_cookie # retrieve the locale end def default_url_options(options = {}) options.merge(:lang => locale_from_cookie) end