ruby-on-rails – 当电子邮件地址以“.old”结尾时,尽量避免发送电子邮件

我要求覆盖ActionMailer的邮件方法.这个方法受到保护所以在子类中,我还将mail方法定义为protected:
protected

def mail(headers={},&block)
  #add a check to avoid sending emails that end with ".old"
  unless headers[:to] =~ /\.old$/
    super(headers,&block)
  end
end

这样,当外发电子邮件地址以.old结尾时,该方法应返回nil而不发送电子邮件.

但是,在我的单元测试中,似乎电子邮件仍然是ActionMailer :: Base.deliveries

这是我的单元测试:

describe 'BaseNotifier' do

  class TestNotifier < BaseNotifier
    def mailer(to,from,subject)
      mail(:to => to,:from => from,:subject => subject)
    end
  end

  before(:each) do
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries.clear
  end

  it "should not send emails to a user with an email that ends in '.old'" do
    TestNotifier.mailer("some_email@gmail.com.old","from@gmail.com","test email").deliver
    puts "what do we have here " + ActionMailer::Base.deliveries.first.to_s
    ActionMailer::Base.deliveries.length.should == 0
  end
end

我创建了一个测试类,并为重写邮件的类创建子类(这是它在系统中的使用方式).然后我发一封电子邮件调用.deliver方法.

更新:我认为交付方法不是问题.当我这样做:放入TestNotifier.mailer(“some_email@gmail.com.old”,“from @gmail.com”,“测试电子邮件”)我收到如下相同的电子邮件.我也尝试以这种方式覆盖mail方法

def mail(headers={},&block)
  else
    super({:to=>nil,:from=>nil,:boundary =>nil,:date => nil,:message =>nil,:subject =>nil,:mime_version => nil,:content_type => nil,:charset =>nil,:content_transfer_encoding => nil},&block)
  end

end

这给了我一个未定义的方法失败’ascii_only?’对于nil:NilClass在这一行:TestNotifier.mailer(“some_email@gmail.com.old”,“测试电子邮件”).

更新:我也尝试使用重写的邮件方法

#create一个覆盖传递方法的类,什么都不做.
class NonSendingEmail; def交付;结束;结束

def mail(headers = {},& block)
#add检查以避免发送以“.old”结尾的电子邮件
除非标题[:to] =〜/ .old $/
super(标题和&块)
其他
NonSendingEmail.new
结束
结束

但我仍然有相同的结果.

似乎传递方法正在生成一个空的电子邮件?我想做的是什么都没有产生.这是来自deliveryies数组的电子邮件

Date: Thu,19 Jan 2012 00:00:00 +0000
Message-ID: <4f18344f94d0_12267803589ac2731d@Ramys-MacBook-Pro.local.mail>
Mime-Version: 1.0
Content-Type: text/plain
Content-transfer-encoding: 7bit

解决方法

你正在编辑错误的地方.将邮件方法更改为返回nil将无济于事,因为邮件程序然后使用空消息.你可以改为修补邮件类(使用rails 3):
module Mail
  class Message
    alias :old_deliver :deliver
    def deliver
      old_deliver unless to.first =~ /\.old$/
    end
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...