Skip to content

Instantly share code, notes, and snippets.

@indrekj
Created July 23, 2012 15:23
Show Gist options
  • Save indrekj/3164215 to your computer and use it in GitHub Desktop.
Save indrekj/3164215 to your computer and use it in GitHub Desktop.
Separating domain logic: emails?
# I'm trying to follow advice from "Keynote: Architecture the Lost Years by Robert Martin"
# ( https://www.youtube.com/watch?v=WpkDN78P884 )
#
# I created a separate gem for my domain logic. It has entities and interactors.
#
# An example of a rails controller:
class CommentsController < ApplicationController
include MyApp::Interactors
def create
# current_user is passed to every interactor so that we can check permissions.
post = FindsPosts.new(current_user).find(params[:id])
comment_params = params[:comment].slice(:body)
comment = CreatesComment.new(post, current_user).create(comment_params)
redirect_to post_path(post.id)
end
end
# An example of an interactor
class CreatesComment
def initialize(post, user)
@post = post
@user = user
@post_owner = post.owner
end
def create(attributes)
# Checks if user has permissions to create the post
# Creates the comment
# IMPORTANT: Sends email to the post owner. I only pass ids because it is a delayed job.
EmailQueue.add(@post_owner, :comment_received, @post.id, comment.id)
# ...
end
end
# So far so good.
# Now to the actual email sending part (this is in rails app):
class Notifier < ActionMailer::Base
def comment_received(subject_id, post_id, comment_id)
# How do I fetch subject (receiver), post and comment?
#
# My initial thought was to use interactor, but this is not really an use case.
# This is already a part of an use case that is just executed later.
#
# Second option is to directly fetch it from app using MyApp::Repositories::Post.get(post_id)
# But I don't think that rails app should know about MyApp structure except for interactors.
#
# I also thought that maybe this is application logic and should not be in the rails app. But it
# renders views, and delivers emails so it sound like a delivery mechanism.
#
# UPDATE:
# Just thought about one idea more: Maybe I should pass a complete data structure to the queue
# instead of the ids. So that comment_received method takes one parameter and inside it there are
# primitive attributes: (subject_email, comment_body, etc)
#
# Any ideas how to handle this?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment