ruby - How to work with an instance of a model without saving it to mongoid -
the users of rails app receiving lot of emails (lets represent signups new customers of users). when email received customer should created, , email should saved well. however, if customer exists (recognized email address of email), email email should not saved database. thought handled email.new
, , save
if email address recognized. seems email.new
saves record database. how work email before deciding wether want save it?
example code:
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 want create new instance of email without saving 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 want save email if passes 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
i'm going suggest fundamental reworking of function. try rewriting function this:
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
you won't able drop code in , expect work, because you'd have define is_spam?
, is_duplicate?
, can @ least see i'm coming from.
i'd recommend writing automated tests these functions if haven't already. pin down problem.
Comments
Post a Comment