开发者

How to set defaults for parameters of url helper methods?

开发者 https://www.devze.com 2023-03-11 02:48 出处:网络
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

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

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).

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?

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


Ryan Bates covered this in todays railscast: http://railscasts.com/episodes/138-i18n-revised

You find the source for url_for here: http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

You will see it merges the given options with url_options, which in turn calls default_url_options.

Add the following as private methods to your application_controller.rb and you should be set.

def locale_from_cookie
  # retrieve the locale
end

def default_url_options(options = {})
  {:lang => locale_from_cookie}
end


doesterr below has almost got it. That version of default_url_options won't play nice with others. You want to augment instead of clobber options passed in:

def locale_from_cookie
  # retrieve the locale
end
    
def default_url_options(options = {})
  options.merge(:lang => locale_from_cookie)
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

The code for url_for is in actionpack/lib/routing/url_for.rb in Rails 3.0.7

0

精彩评论

暂无评论...
验证码 换一张
取 消