by typicalrunt · 13y ago · 0 comments
A simpler, more contrived example, would be to create a new function create_and_send_email! and place the creation logic and email sending logic in there. And now, when the developer uses the service object, she has the ability to choose between just creating the contact, or creating it and sending an email.
class CreatesContact
def initialize(contact)
@contact = contact
end
def create_contact!
@contact.save
end
def create_contact_and_send_email!
create_contact!
deliver_contact_created_email
end
end class CreateContact
def initialize contact_jack, email_jack
@contact_jack = contact_jack
@email_jack = email_jack
end
def do input
# validate input
contact = Contact.new
contact.populate input
contact_jack.save contact.to_hash
email = ContactEmail.new
email.populate contact.to_hash
email_jack.send email.to_hash
contact.to_hash
end
end
With that structure you can call CreateContact with: action = CreateContact.new
result = action.do ContactJack.new, EmailJack.new
In that structure you can totally test the action and logic without hitting the db or the mail system at all. Your ContactJack and EmailJack can be easily swapped out for various pluggable data stores. Fileystem, MySQL, Mongo, Postgres, Cassandra, could be swapped out for the ContactJack. EmailJack could send through standard mail servers, SendGrid, Amazon AWS, Mandrill, etc.Obvious is on github, you can read more at http://obvious.retromocha.com
create_contact!(:send_email => false)Plus he should probably just break the send_email method into it's own method, which he can then call depending on if create_contact returns successfully.