2011-06-08 191 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 
相關問題