How to access specific model in rails config/production.rb file?

395 views Asked by At

I want to send exception mail to email_ids stored in yb_notifier_email_ids table. Previously, email_id was hardcoded in production.rb file. I want to send mail by using model. But as configurations file are loaded before active_records I am not able to do this.

-----------migration

        class CreateYbNotifierEmailIds < ActiveRecord::Migration
          def change
            create_table :yb_notifier_email_ids do |t|
              t.string :email_id

              t.timestamps null: false
            end
          end
        end

----------------------------required------------

        config.middleware.use ExceptionNotification::Rack,
            :email => {
              :email_prefix => "[YB] ",
              :sender_address => %{"YB Notifier" <[email protected]>},
              :exception_recipients => YbNotifierEmailIds.pluck(:email_id)
            }
        end

-----------------------I have tried this:

        Rails.application.middleware.use ExceptionNotification::Rack,
              :email => {
                :email_prefix => "[YB-QA] ",
                :sender_address => %{"YB Notifier" <[email protected]>},
                :exception_recipients => defined?(YbNotifierEmailId) && YbNotifierEmailId.table_exists? ? YbNotifierEmailIds.pluck(:email_id) : %w{[email protected]}
        
            }

but defined?(YbNotifierEmailId) && YbNotifierEmailId.table_exists? this condition is getting failed.

2

There are 2 answers

0
Somebody_ror On BEST ANSWER

This is resolved using lambda. lambda {TableName.pluck(:email_id)}. Thanks

9
ferrisoxide On

Have you considered moving this code to an initializer (i.e. a new file under the config/initializers folder) just containing your setup code for the middleware?

You'll have access to the models in code run at this point. You'll probably need the form Rails.application.middleware.use, per your last example ("have tried this:") - that should work, though I haven't explicitly checked this.

Something like a file named config/initializers/exception_notification.rb containing just your middleware setup:

Rails.application.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[YB] ",
    :sender_address => %{"YB Notifier" <[email protected]>},
    :exception_recipients => YbNotifierEmailIds.pluck(:email_id)
  }