How to set defaults for parameters of url helper methods?

后端 未结 3 1478
盖世英雄少女心
盖世英雄少女心 2021-02-06 07:15

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
         


        
3条回答
  •  耶瑟儿~
    2021-02-06 08:00

    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

提交回复
热议问题