Skip to content

Instantly share code, notes, and snippets.

@elskwid
Last active August 29, 2015 14:07
Show Gist options
  • Save elskwid/ba30db877ac2034e3c4e to your computer and use it in GitHub Desktop.
Save elskwid/ba30db877ac2034e3c4e to your computer and use it in GitHub Desktop.
Little domain service thing
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
# 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