我的Rails应用程序的用户收到了很多电子邮件(假设他们代表我的用户的新客户注册)。收到电子邮件后,应创建一个客户,同时也应保存该电子邮件。但是,如果客户已存在(通过电子邮件的电子邮件地址识别),则不应将电子邮件保存到数据库。我认为这是由Email.new
处理的,然后只有save
才能识别电子邮件地址。但似乎Email.new
将记录保存到数据库中。那么在实际决定之前我如何处理电子邮件呢?我想保存它?
示例代码:
class Email
include Mongoid::Document
field :mail_address, type: String
belongs_to :user, :inverse_of => :emails
belongs_to :customer, :inverse_of => :emails
def self.receive_email(user, mail)
puts user.emails.size # => 0
email = Email.new(mail_address: mail.fetch(:mail_address), user: user) # Here I want to create a new instance of Email without saving it
puts user.emails.size # => 1
is_spam = email.test_if_spam
return is_spam if is_spam == true
is_duplicate = email.test_if_duplicate(user)
end
def test_if_spam
spam = true if self.mail_address == "spam@example.com"
end
def test_if_duplicate(user)
self.save
customer = Customer.create_or_update_customer(user, self)
self.save if customer == "created" # Here I want to save the email if it passes the customer "test"
end
end
class Customer
include Mongoid::Document
field :mail_address, type: String
belongs_to :user, :inverse_of => :customers
has_many :orders, :inverse_of => :customer
def self.create_or_update_customer(user, mail)
if user.customers.where(mail_address: mail.mail_address).size == 0
customer = mail.create_customer(mail_address: mail.mail_address, user: user)
return "created"
end
end
end
答案 0 :(得分:0)
我将建议对你的功能进行一些基本的改造。尝试重写你的功能:
class Email
def self.save_unless_customer_exists(user, mail)
email = Email.new(
mail_address: mail.fetch(:mail_address),
user: user
)
return if email.customer or email.is_spam? or email.is_duplicate?
Customer.create!(user: user)
email.save!
end
end
您将无法删除该代码并希望它能够正常运行,因为您必须定义is_spam?
和is_duplicate?
,但希望您至少可以看到我在哪里来自。
如果你还没有,我还建议为这些功能编写一些自动化测试。它可以帮助你解决问题。