如何设置 url helper 方法参数的默认值? [英] How to set defaults for parameters of url helper methods?
问题描述
我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1
.这就是我在 routes.rb 中所做的:
I use language code as a prefix, e.g. www.mydomain.com/en/posts/1
.
This is what I did in routes.rb:
scope ":lang" do
resources :posts
end
现在我可以轻松使用 url 助手,例如:post_path(post.id, :lang => :en)
.问题是我想在 cookie 中使用一个值作为默认语言.所以我可以只写 post_path(post.id)
.
Now I can easily use url helpers such as: post_path(post.id, :lang => :en)
. The problem is that I would like to use a value in a cookie as a default language. So I could write just post_path(post.id)
.
有什么办法可以为 url helper 中的参数设置默认值?我找不到 url helper 的源代码 - 有人能指出我正确的方向吗?
Is there any way how to set default values for parameters in url helpers? I can't find the source code of url helpers - can someone point me in the right direction?
另一种方式:我已经尝试在 routes.rb 中设置它,但它仅在启动时进行评估,这对我不起作用:
Another way: I have already tried to set it in routes.rb but it's evaluated in startup time only, this does not work for me:
scope ":lang", :defaults => { :lang => lambda { "en" } } do
resources :posts
end
推荐答案
这是我脑中的编码,所以不能保证,但在初始化程序中尝试一下:
This is coding from my head, so no guarantee, but give this a try in an initializer:
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)
或者直接的猴子补丁...
or straight monkey-patch...
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 中
The code for url_for is in actionpack/lib/routing/url_for.rb in Rails 3.0.7
这篇关于如何设置 url helper 方法参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!