简体   繁体   中英

Is there an alternative to using Rails.env?

In my controller, I have a section that creates an email and sends it out, but I want that feature to be only available on production.

email = PortalEmail.new(params[:portal][:email]) if Rails.env.production? && PortalEmail.app_or_site?(@object)

Is there a better way to do this? Perhaps within the configuration/environments folder?

Any thoughts would be appreciated.

Testing Rails.env.production? is the best and most concise way to conditionally execute code only in your production environment.

That said, you should remove the conditional code from your controller and instead configure a fake MTA to receive email outside of the production environment. For example, MailCatcher provides a fake MTA which will "catch" any mail sent by your development environment and hold on to it, for you to inspect in their web-based UI.

It's typically better to configure your app to use fake dependencies in development, than to litter your code with conditional environment checks.

I would prefer to use flags set in application.rb like this:

# application.rb
config.can_send_mail = false

# production.rb
config.can_send_mail = true

Then use

email = PortalEmail.new(params[:portal][:email]) if Rails.application.config.can_send_mail && PortalEmail.app_or_site?(@object)

to avoid littering my app with references to the environment. This makes it easier when you later add a new environment (like a staging environment) that needs to send email too.

You can use letter_opener to preview emails in browser when running in development mode.

Just add it under the development group and you can configure it like this:

# config/environments/development.rb

config.action_mailer.delivery_method = :letter_opener

And you won't need that conditional anymore.

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