2011-06-08 112 views
5

我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1。 这是我在routes.rb中做的:如何为url helper方法的参数设置默认值?

scope ":lang" do 
    resources :posts 
end 

现在我可以很容易地使用URL佣工如:post_path(post.id, :lang => :en)。问题是我想将Cookie中的值用作默认语言。所以我可以只写post_path(post.id)

有什么办法如何设置默认值的参数在URL助手?我无法找到url helpers的源代码 - 有人能指出我正确的方向吗?

另一种方式:我已经尝试将其设置在routes.rb中,但它的启动时间只计算,这并没有为我工作:

scope ":lang", :defaults => { :lang => lambda { "en" } } do 
    resources :posts 
end 

回答

3

这是从我的头编码,所以无法保证但让这个尝试在初始化:

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的ActionPack的/ lib目录/路由/ url_for.rb 3.0.7

+0

酷,我不知道url_for被称为每次网址助手被称为!谢谢。 – 2011-06-08 17:37:53

+0

虽然有多个url_for方法。我必须将我的url_for移动到ApplicationController并将其设置为helper_method,否则它不起作用。但无论如何,你的想法有帮助,谢谢。 – 2011-06-10 07:13:20

+0

最上面的方法不起作用,因为你试图在新模块中不存在的方法 – 2013-05-24 06:22:58

6

瑞恩·贝茨覆盖这个在今天railscast:http://railscasts.com/episodes/138-i18n-revised

你找到源url_for这里:http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

您会看到它会将给定的选项与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 
3

以上几乎没有得到它。那个版本的default_url_options不会和其他人玩。你想,而不是扩充的传入撞选项:

def locale_from_cookie 
    # retrieve the locale 
end 

def default_url_options(options = {}) 
    options.merge(:lang => locale_from_cookie) 
end 
相关问题