Last active
October 6, 2015 08:37
-
-
Save vkuznetsov/3192c051faaf3b81d56c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# В местах вызова сервисов (в контроллерах) | |
def register_user_account(order) | |
order.transaction do | |
account = order.register_account(guest_header) | |
Account::InitializeAccount.call(account: account) | |
account | |
end | |
end | |
# Добавляем вызов unit_of_work | |
def register_user_account(order) | |
UnitOfWork.transaction do | |
account = order.register_account(guest_header) | |
Account::InitializeAccount.call(account: account) | |
account | |
end | |
end | |
class UnitOfWork | |
def self.current | |
Thread.current[:unit_of_work] | |
end | |
def self.transaction | |
Thread.current[:unit_of_work] = UnitOfWork.new | |
yield | |
current.commit | |
end | |
def register_dirty(object) | |
@dirty_objects << object | |
end | |
def register_new(object) | |
@new_objects << object | |
end | |
def register_deleted(object) | |
@deleted_objects << object | |
end | |
def commit | |
@new_objects.each(&:save) | |
@dirty_objects.each(&:save) | |
@deleted_objects.each(&:delete) | |
end | |
end | |
module ServiceExtension | |
def register_dirty(object, changes) | |
unit_of_work = UnitOfWork.current | |
if unit_of_work | |
unit_of_work.register_dirty object | |
apply_changes_to_object(changes) | |
else | |
object.send(:update_attributes, changes) | |
end | |
end | |
end | |
# Тогда в сервисах типа Account::InitializeAccount.call | |
# Вместо | |
user.update_attribute(:mdp_household_id, household_id) | |
# Пишем | |
register_dirty(user, mdp_household_id: household_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment