Skip to content

Instantly share code, notes, and snippets.

@nicholasjhenry
Created June 30, 2012 16:34
Show Gist options
  • Save nicholasjhenry/3024550 to your computer and use it in GitHub Desktop.
Save nicholasjhenry/3024550 to your computer and use it in GitHub Desktop.
Hexagonal Rails Example
class AddComment
attr_reader :observer, :store, :success, :fail
def initializer(observer, store)
@observer, @store = observer, store
yield self if block_given?
return self
end
def call(post_id, comment_attrs)
post = store.find(post_id)
comment = post.add_comment(comment_attrs)
if comment.save
observer.success.call(post, comment)
else
observer.fail.call(post, comment)
end
end
end
class CommentController
def create
service = MyApp::AddComment.new(self, Post) do |service|
service.success = on_create_success
service.fail = on_create_fail
end
service.call(post_id: 1, comment: { body: "cool!"})
end
private
def on_create_success(post, comment)
-> { |post, comment| redirect_to post }
end
def on_create_fail(post, comment)
-> { |post, comment| @post, @comment = post, comment; render :new }
end
end
@krisleech
Copy link

I like the idea of passing the store to the service object. I forked this gist and updated it to use the Wisper gem for the observer part, here is the diff.

If your interested there are other examples on the wiki 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment