set default_url_options on initialize

10,184

The answer is...it's impossible because default_url_options is implemented as a function, not an attr.

From action_pack/action_controller/base.rb:1053:

  # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in
  # the form of a hash, just like the one you would use for url_for directly. Example:
  #
  #   def default_url_options(options)
  #     { :project => @project.active? ? @project.url_name : "unknown" }
  #   end
  #
  # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the
  # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set
  # by this method.
  def default_url_options(options = nil)
  end
Share:
10,184
Ben K.
Author by

Ben K.

Updated on June 04, 2022

Comments

  • Ben K.
    Ben K. almost 2 years

    I need to force the host in one of the environments in my rails app.

    I've can get the override to work by including

      def default_url_options(opts={})
       opts.merge({:host => 'stg.my-host.com'})
      end
    

    in app/controllers/application.rb

    But is there a way to set this on initialize, preferably in a config/environments/... file? I'd like to keep conditional env logic out of the controller.

    But when I try

       config.action_controller.default_url_options = { ... }
    

    or even

    ActionController::Base.default_url_options = { ... }
    

    I get "undefined method," even if a wrap in a config.after_initialize { ... }

    any thoughts?