set default_url_options on initialize

岁酱吖の 提交于 2019-12-10 17:00:08

问题


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?


回答1:


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



回答2:


You can force the configuration this way:

config.action_mailer.default_url_options = { :host => "foo.com" }

The problem in your code is that you've used config.action_controller instead of config.action_mailer



来源:https://stackoverflow.com/questions/3928622/set-default-url-options-on-initialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!