Skip to content

Instantly share code, notes, and snippets.

@mikepack
Forked from justinwiley/dci-rest-creation.rb
Created January 26, 2012 20:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mikepack/1685027 to your computer and use it in GitHub Desktop.
Save mikepack/1685027 to your computer and use it in GitHub Desktop.
DCI + Rails new and create
# ---role
module BookManager
def create_book(attrs)
self.books.create! attrs
end
def update_book(book_id,attrs)
book = self.books.find(book_id)
book.update_attributes attrs
end
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)
@user.extend BookManager
end
end
class AddingBookContext < BookModifyingContext
def execute(attrs)
@user.create_book(attrs)
end
end
class UpdateBookContext < BookModifyingContext
def execute(id,attrs)
@user.update_book(id,attrs)
end
end
class DeletingBookContext < BookModifyingContext
def execute(id)
@user.delete_book(id)
end
end
# ---controller
class BookController < ApplicationController
def index
@books = Book.all
end
def new
@book = Book.new
end
def create
AddBookContext.execute(params[:book])
end
def edit
@book = Book.find(params[:id])
end
def update
UpdateBookContext.execute(params[:id], params[:book])
end
def destroy
DeleteBookContext.execute(params[:id])
end
end
@andredublin
Copy link

any reason why is plural? shouldn't it match the attr_accessor symbol?

self.books.create! attrs 

@vmoravec
Copy link

vmoravec commented Jan 6, 2013

@dublinan BookManager extends the @user, not the context. The model User has expressed ActiveRecord association has_many :books which is not shown in that gist.

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