Skip to content

Instantly share code, notes, and snippets.

@i2chris
Last active July 19, 2018 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save i2chris/247b975aa44639a3383999dc62d1084d to your computer and use it in GitHub Desktop.
Save i2chris/247b975aa44639a3383999dc62d1084d to your computer and use it in GitHub Desktop.
class QuoteGroupsController << QuotingController
...
def add_tests
Services::AddTestsToQuoteGroup.new.call(
attempt_id: params[:attempt_id],
test_ids: params[:test_ids],
quote_group_id: params[:quote_group_id],
) do |result|
result.failure do |errors|
render status: 500, json: errors
end
result.success do
render json: {message: "ok"}
end
end
end
...
end
module Quoting
module Services
class AddTestsToQuoteGroup < Service
Schema = Dry::Validation.Params do
configure do
def self.messages
super.merge(
en: {errors: {
attempt_is_preliminary: "Quote Attempt must be preliminary",
tests_are_active: "All tests must be active",
quote_group_is_active: "Selected quote group must be active",
}},
)
end
end
required(:attempt_id).filled(:int?)
required(:quote_group_id).filled(:int?)
required(:test_ids, Types::Integer).filled(:array?)
validate(attempt_is_preliminary: [:attempt_id]) do |attempt_id|
Attempt.find(attempt_id).preliminary?
end
validate(tests_are_active: [:test_ids]) do |test_ids|
Testing::Test.find_active(test_ids).count == test_ids.size
end
validate(quote_group_is_active: [:attempt_id, :quote_group_id]) do |attempt_id, quote_group_id|
quote_group = Attempt.find(attempt_id).quote_groups.find(quote_group_id)
!quote_group.expired? && !quote_group.group_placeholder.expired?
end
end
def call(attempt_id:, test_ids:, quote_group_id:)
result = Schema.({
attempt_id: attempt_id,
test_ids: test_ids,
quote_group_id: quote_group_id,
})
if result.errors.any?
Failure(result.errors)
else
attempt = Attempt.find attempt_id
...
...
Success(quote_group)
end
end
end
end
end
-------
require 'dry-monads'
require 'dry/matcher/result_matcher'
require "dry-validation"
class Service
include Dry::Monads::Result::Mixin
class ServiceFailed < StandardError ; end
def self.inherited(base)
super
base.include(Dry::Matcher.for(:call, with: Dry::Matcher::ResultMatcher))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment