-
-
Save mikepack/1685027 to your computer and use it in GitHub Desktop.
DCI + Rails new and create
This file contains 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
# ---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 |
@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
any reason why is plural? shouldn't it match the attr_accessor symbol?