Service model callbacks
This commit is contained in:
@@ -4,6 +4,38 @@ class ApplicationService
|
|||||||
include ActiveModel::Model
|
include ActiveModel::Model
|
||||||
include ActiveModel::Attributes
|
include ActiveModel::Attributes
|
||||||
|
|
||||||
|
define_model_callbacks :perform
|
||||||
|
define_model_callbacks :success, only: [:after]
|
||||||
|
define_model_callbacks :failure, only: [:after]
|
||||||
|
|
||||||
|
@prepend_methods = Module.new do
|
||||||
|
def perform(...)
|
||||||
|
status = run_callbacks :perform do
|
||||||
|
super(...)
|
||||||
|
end
|
||||||
|
|
||||||
|
if status
|
||||||
|
run_callbacks :success
|
||||||
|
else
|
||||||
|
run_callbacks :failure
|
||||||
|
end
|
||||||
|
|
||||||
|
status
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.inherited(subclass)
|
||||||
|
super
|
||||||
|
subclass.prepend @prepend_methods
|
||||||
|
end
|
||||||
|
|
||||||
|
before_perform do
|
||||||
|
if invalid?
|
||||||
|
logger.debug 'Validation failed'
|
||||||
|
throw :abort
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def perform
|
def perform
|
||||||
# Override this
|
# Override this
|
||||||
end
|
end
|
||||||
@@ -13,4 +45,8 @@ class ApplicationService
|
|||||||
def save(model)
|
def save(model)
|
||||||
model.save.tap { @errors = model.errors }
|
model.save.tap { @errors = model.errors }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def logger
|
||||||
|
@logger ||= ActiveSupport::TaggedLogging.new(Rails.logger).tagged(self.class.name)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ module Tasks
|
|||||||
attribute :description, :string
|
attribute :description, :string
|
||||||
attribute :status_id, :integer
|
attribute :status_id, :integer
|
||||||
|
|
||||||
validates :project_id, :title, presence: true
|
validates :project_id, :title, :status_id, presence: true
|
||||||
|
|
||||||
delegate :model_name, to: Task
|
delegate :model_name, to: Task
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user