Created
June 30, 2012 16:34
-
-
Save nicholasjhenry/3024550 to your computer and use it in GitHub Desktop.
Hexagonal Rails Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 😄