在初始化时设置default_url_options [英] set default_url_options on initialize
问题描述
我需要在我的rails应用程序中的一种环境下强制主机.
I need to force the host in one of the environments in my rails app.
我可以通过添加
def default_url_options(opts={})
opts.merge({:host => 'stg.my-host.com'})
end
在app/controllers/application.rb
in app/controllers/application.rb
但是有没有办法在初始化时设置它,最好在config/environments/...文件中?我想将条件环境逻辑排除在控制器之外.
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.
但是当我尝试
config.action_controller.default_url_options = { ... }
甚至
ActionController::Base.default_url_options = { ... }
即使配置中包含换行符,我也会得到未定义的方法".after_initialize {...}
I get "undefined method," even if a wrap in a config.after_initialize { ... }
有什么想法吗?
推荐答案
答案是...这是不可能的,因为default_url_options是作为函数而不是attr实现的.
The answer is...it's impossible because default_url_options is implemented as a function, not an attr.
来自action_pack/action_controller/base.rb:1053:
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
这篇关于在初始化时设置default_url_options的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!