Created
October 13, 2017 14:49
-
-
Save renatoalencar/3c5fb5b3834e481c80b27904f5d78744 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
| class ApplicationService | |
| class ServiceValidation | |
| def initialize(opts = {}) | |
| @method = opts[:method] | |
| @message = opts[:message] | |
| @exception = opts.fetch(:exception, Errors::ServiceError) | |
| end | |
| def validate | |
| unless yield @method | |
| raise_exception | |
| end | |
| end | |
| private | |
| def raise_exception | |
| raise @exception, @message | |
| end | |
| end | |
| class ModelValidation < ServiceValidation | |
| def initialize(opts = {}) | |
| super( | |
| method: opts[:method], | |
| exception: Errors::ModelValidationError | |
| ) | |
| end | |
| def validate | |
| super do |method| | |
| object = yield method | |
| valid = object.valid? | |
| @message = object.errors.full_messages.first | |
| valid | |
| end | |
| end | |
| end | |
| class << self | |
| def validations | |
| @validations ||= Array.new | |
| end | |
| def validates(method, message, exception = Errors::ServiceError) | |
| validations << ServiceValidation.new( | |
| method: method, | |
| message: message, | |
| exception: exception | |
| ) | |
| end | |
| def validate_model(attribute) | |
| validations << ModelValidation.new(method: attribute) | |
| end | |
| end | |
| def validate | |
| self.class.validations.each do |validation| | |
| validation.validate do |method| | |
| send(method) | |
| end | |
| end | |
| end | |
| def perform | |
| validate | |
| yield if block_given? | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment