Sha256: bf4cc183bb023bbfb611f3150284d0c8586cbfc28dde9d35bb42468fca57ca29

Contents?: true

Size: 1.05 KB

Versions: 9

Compression:

Stored size: 1.05 KB

Contents

module RestfulResource
  module RailsValidations
    module ClassMethods
      def put(id, data: {}, **others)
        with_validations(id, data: data) { super }
      end

      def patch(id, data: {}, **others)
        with_validations(id, data: data) { super }
      end

      def post(data: {}, **)
        with_validations(data: data) { super }
      end

      def get(**)
        with_validations { super }
      end

      def delete(id, **)
        with_validations { super }
      end

      private

      def with_validations(id = nil, data: {})
        yield
      rescue HttpClient::UnprocessableEntity => e
        errors = parse_json(e.response.body)
        result = if errors.is_a?(Hash) && errors.key?('errors')
                   data.merge(errors)
                 else
                   data.merge(errors: errors)
                 end

        result = result.merge(id: id) if id

        new(result)
      end
    end

    def self.included(base)
      base.extend(ClassMethods)
    end

    def valid?
      @inner_object.errors.nil?
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
restful_resource-2.18.2 lib/restful_resource/rails_validations.rb
restful_resource-2.18.1 lib/restful_resource/rails_validations.rb
restful_resource-2.18.0 lib/restful_resource/rails_validations.rb
restful_resource-2.17.0 lib/restful_resource/rails_validations.rb
restful_resource-2.16.0 lib/restful_resource/rails_validations.rb
restful_resource-2.15.0 lib/restful_resource/rails_validations.rb
restful_resource-2.14.0 lib/restful_resource/rails_validations.rb
restful_resource-2.13.4 lib/restful_resource/rails_validations.rb
restful_resource-2.13.3 lib/restful_resource/rails_validations.rb