Rails: move some logic from models

Example

class BooksController  
def create
@book = Book.create(params[:book])
end
end

class Book < ActiveRecord::Base
before_create :get_papers
after_create :print
after_save :notify_readers, if: -> { Config.notifications.enabled? }

def notify_readers
Notification.new.
notify_about_new_book(self, self.readers)
end
end

Disadvantages

Alternative way

class BooksController  
def create
@book = BookCreateService.execute(params[:book])
end
end

class Book < ActiveRecord::Base
end

class BookCreateService
def self.execute(book_params)
@book = Book.new(book_params)

if @book.get_papers && @book.save
@book.print

if Config.notifications.enabled?
Notification.new.notify_about_new_book(book, book.readers)
end
end

@book
end
end

Used in a real world?


Dmitriy Zaporozhets

Written by

Ruby developer, GitLab cofounder

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade