简体   繁体   中英

How to set default_url_options in a DRY manner?

I want to set some of the options on config.action_mailer.default_url_options in an initializer. However, the problem is that this value may be nil , or it may be a hash with other options.

Example of the problem when using the reccomended method:

# config/application.rb
config.action_mailer.default_url_options = {protocol: 'https'}

# config/environments/production.rb
config.action_mailer.default_url_options = {host: "example.com"}

# config/environments/development.rb
config.action_mailer.default_url_options = {host: "staging.example.com"}

Now default_url_options doesn't have ssl: true set.

The only way to accommodate both possibilities as far as I can tell is to set it to an empty hash if it's null, then add to the hash like so:

config.action_mailer.default_url_options ||= {}
config.action_mailer.default_url_options[:host] = 'example.com'

This is not dry, and has to be done anywhere you wish to set this option unless you are absolutely sure none of the options have been set before and nobody will attempt to set one of the options in the future in a file which is loaded before this one.

Is there a better way to do this?

您可以在env文件中执行类似操作。

config.action_mailer.default_url_options.merge(host: "staging.example.com")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM