Toshi
Toshi

Reputation: 6342

Best way to change the behavior depending on the environment variables in Rails

I sometimes face the situation which could be better to handle flow differently depending on the environment. (Ex. disable some features)

For example. If you are on the production, you can send a email if the process is succeeded. But for test, and development environment we just simply disable it.

For now, I just put if-clause.

  ActiveRecord::Base.transaction do
    itemable = create_invoiceitemable(each_line)
    next unless itemable.present?

    create_invoiceitem(invoice, itemable, each_line[:id])
  end
  ReceiptMailer.receipt(invoie[:uuid]).deliver_later if RAILS_ENV[:production]

Any ideas for better way to handle this?

Upvotes: 1

Views: 292

Answers (2)

Rada Bogdan
Rada Bogdan

Reputation: 352

Instead of relying on the name of the environment to check if something should be activated or not ..why not use a environment variable which You can set its value în the environment specific file and check its value instead.

This way if You for example deploy your app on Heroku You can enable or disable this 'feature without touching the code or re-deploy every time since this are all available from the interface or command line.

I personally think this is a good approach. There might be other good approaches also.

You can use different gems like dotenv to accomplish this . There might be other gems out there too.

Hope this will help :)

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

It is impossible to answer an exact question, since it’s heavily opinion-based, but you might find useful stubbing such methods with:

config/initializers/stubs.rb

ReceiptMailer.prepend(Module.new do
  def receipt(*args)
    Logger.info "ReceiptMailer#receipt called with #{args.inspect}"
    Hashie::Mash.new { deliver_later: nil } # to allow call
  end
end) unless RAILS_ENV[:production]

Upvotes: 1

Related Questions