Skip to content

Instantly share code, notes, and snippets.

@justinko
Created January 9, 2012 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinko/1585371 to your computer and use it in GitHub Desktop.
Save justinko/1585371 to your computer and use it in GitHub Desktop.
The value of contexts in DCI
class PostCreationContext
def initialize(post)
@post = post
@post.extend PostNotifier
@post.extend PostIndexer
@post.extend PostCacher
end
def execute
@post.save
@post.notify
@post.index
@post.cache
end
end
class PostsController < ApplicationController
def create
post = Post.new
post.extend PostNotifier
post.extend PostIndexer
post.extend PostCacher
post.save
post.notify
post.index
post.cache
end
end
# VS
class PostsController < ApplicationController
def create
context = PostCreationContext.new(Post.new)
context.execute
end
end
@rkh
Copy link

rkh commented Jan 12, 2012

By "separation", you mean classes vs modules?

I mean composition vs inheritance.

But there is overhead to that approach...

Agreed. But you avoid leaky abstractions.

Define your own delete method in a "role" (module). Use super to hit the persistence layer delete method.

What if some code on the persistent layer wants to call delete and by that means "remove from the database" vs. some business logic code that calls delete and means "remove from the user interface"?

@justinko
Copy link
Author

Agreed. But you avoid leaky abstractions.

The leakiness potential is worth not having an extra layer.

What if some code on the persistent layer wants to call delete and by that means "remove from the database" vs. some business logic code that calls delete and means "remove from the user interface"?

This is a scenario that I just don't think will come up. When would you ever need to call a delete method on the extended object and then actually need to delete it in the db? A more real life scenario would be calling an archive method then the delete method.

This is all just experimentation for me. I might switch to composition if it gets painful - we'll see.

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