Skip to content

Instantly share code, notes, and snippets.

@justinwiley
Created January 26, 2012 19:46
Show Gist options
  • Save justinwiley/1684659 to your computer and use it in GitHub Desktop.
Save justinwiley/1684659 to your computer and use it in GitHub Desktop.
DCI + Rails new and create
# ---role
module BookCreater
def create_book(attrs)
self.books.create! attrs
end
end
module BookUpdater
def update_book(book_id,attrs)
book = self.books.find(book_id)
book.update_attributes attrs
end
end
module BookViewer
def my_books
self.books
end
end
module BookDeleter
def delete_book(id)
self.books.find(id).destroy
end
end
# ---context
class BookModifyingContext
attr_accessor :user, :book
def initialize(user_id)
@user = User.find(user_id)
end
end
class AddingBookContext < BookModifyingContext
def initialize
super
@book = Book.new(:user => @user)
@user.extend BookCreater
end
def execute(attrs)
@user.create_book(attrs)
end
end
class UpdateBookContext < BookModifyingContext
def initialize
@user.extend BookUpdater
end
def execute(id,attrs)
@user.update_book(id,attrs)
end
end
class DeletingBookContext < BookModifyingContext
def initialize
@user.extend BookDeleter
end
def execute(id)
@user.delete_book(id)
end
end
class ViewingBookContext < BookModifyingContext
def initialize
@user.extend BookViewer
end
def execute
@user.my_books
end
end
# ---controller
class BookController < ApplicationController
before_filter :set_context, :only => [:new,:create]
def index
context = DeletingBookContext.new(params[:id])
context.execute params[:book][:id]
end
def new
@book = @adding_book_context.book
end
def create
@adding_book_context.execute(params[:book])
end
def update
context = UpdateBookContext.new(params[:id],params[:book])
context.execute params[:book]
end
def destroy
context = DeletingBookContext.new(params[:id])
context.execute params[:book][:id]
end
private
def create_context
@adding_book_context = AddingBookContext.new(current_user.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment