Last active
August 29, 2015 14:07
-
-
Save elskwid/ba30db877ac2034e3c4e to your computer and use it in GitHub Desktop.
Little domain service thing
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
require "concord" | |
require "procto" | |
class DomainService < Module | |
def initialize(*attrs, call: :call) | |
@attrs = attrs | |
@call = call | |
end | |
def included(descendant) | |
descendant.send(:include, Procto.call(@call)) | |
descendant.send(:include, Concord::Public.new(*@attrs)) | |
# Define Failure error on module/class | |
descendant.const_set "Failure", failure_error_class | |
end | |
# General Failure from service, defined as a subclass of StandardError. | |
# An object can be passed in so the rescue block can inspect and use | |
# error data. For instance with AR Model errors. | |
def failure_error_class | |
Class.new(StandardError) do | |
include Concord::Public.new(:object) | |
end | |
end | |
end |
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
# Create a service to handle creating an ActiveRecord::Model | |
class MyService | |
include DomainService.new(:attributes) | |
def call | |
model = MyModel.create(params) | |
if model.errors.present? | |
fail Failure.new(model), "Could not create model." | |
end | |
end | |
# Could use strong_params too | |
def params | |
attributes.require(:csv) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment