2017-10-07 61 views
0

Rails 4.1.4,我有很多Mailer類,它們都有不同的傳遞方法。現在這已經導致我一個問題。基於條件的交付方式? Rails

在開發和測試環境的時候,如果我執行和交付使用下面的類,然後交付方式變得:custom_method,即使我已經提到在軌環境文件config.delivery_method = :test我已經DELIVERY_METHOD爲:test然後。

class CustomMailer < ActionMailer::Base 

    default :delivery_method => :custom_method, 
      from: "...", 
      reply_to: '...' 

    def emailer(emails) 
    mail(to: emails, subject: 'test') 
    end 

end 

什麼是開發和測試環境改變:custom_method:test的正確方法嗎?

一個可能的解決方案,我已經實現了它的工作原理是這樣的:

class CustomMailer < ActionMailer::Base 

    DELIVERY_METHOD = Rails.env == 'production' ? :custom_method : :test 

    default :delivery_method => DELIVERY_METHOD, 
      from: "...", 
      reply_to: '...' 

    def emailer(emails) 
    mail(to: emails, subject: 'test') 
    end 

end 

這對我的作品,但我覺得這不是一個好辦法,因爲我必須在此線:

DELIVERY_METHOD = Rails.env == 'production' ? :custom_method : :test 

在每個Mailer類中都可能導致冗餘。如果可以通過一些常見的方式處理,那將會很棒。

請注意,有不同交付方法爲每個梅勒類。

回答

1

你肯定採用的方法的工作原理,但我相信,在你的代碼查詢Rails.env是一個反模式。

您可以改爲使用應用程序配置,方法是設置custom config attribute。這裏有一個例子:

# config/production.rb 
Rails.application.configure do 
    # by having this configured by an environment variable 
    # you can have different values in staging, 
    # develop, demo, etc.. They all use "production" env. 
    config.x.mailer_livemode = ENV['MAILER_LIVEMODE'] 
end 

# config/development.rb 
Rails.application.configure do 
    config.x.mailer_livemode = false 
end 

# config/test.rb 
Rails.application.configure do 
    config.x.mailer_livemode = false 
end 

# app/mailers/custom_mailer.rb 
default delivery_method: Rails.application.config.x.mailer_livemode ? :custom_method : :test 

靈活性是優越的。你可以有更多的一個配置變量一起工作,在配置中直接設置delivery_method等。

最重要的是,你不依賴於某些與你的電子郵件發送無關的東西(Rails.env) 。

+0

更好的方法。 – user1735921

0

如何創建ApplicationMailer並讓所有其他郵件程序從ApplicationMailer繼承?這是Rails5中的方法。下面的代碼顯示了一種可能的方式來定義兒童郵寄者的遞送方法,並從ApplicationMailer繼承選擇邏輯。

class ApplicationMailer < ActionMailer::Base 
    SELECTOR = Hash.new { |h,k| h[k] = k } 
    DELIVERY_METHOD = Rails.env.production? ? :custom_method : :test ##selection logic, use: env, env variables ... 
end 

class UserMailer < ApplicationMailer 
    SELECTOR[:custom_method] = :sendmail ##class-specific delivery method 
    default delivery_method: SELECTOR[DELIVERY_METHOD] 
    ##.... 
end 
+0

':custom method'對於那些將要繼承的類是不常見的 – user1735921

+0

當然。您可以在子類中定義自定義方法,而不是在ApplicationMailer中定義方法。 – EJ2015

+0

那麼當ApplicationMailer中沒有任何東西是常見的時候,它的用法是什麼,我知道這可能是一個好的做法,但它不能解決我的問題,它基本上是我已經提到過的問題中的解決方案,從類繼承它不會有任何區別,因爲我仍然需要多次編寫該代碼。 – user1735921