Sha256: 35b77fc57b29be9f11903cced5ea64904ebf811f8644a217dbb817fc128bd131

Contents?: true

Size: 1 KB

Versions: 6

Compression:

Stored size: 1 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

      private

      def with_validations(id = nil, data: {})
        yield
      rescue HttpClient::UnprocessableEntity => e
        errors = parse_json(e.response.body)
        result = nil
        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

6 entries across 6 versions & 1 rubygems

Version Path
restful_resource-2.8.0 lib/restful_resource/rails_validations.rb
restful_resource-2.7.0 lib/restful_resource/rails_validations.rb
restful_resource-2.6.1 lib/restful_resource/rails_validations.rb
restful_resource-2.5.3 lib/restful_resource/rails_validations.rb
restful_resource-2.5.2 lib/restful_resource/rails_validations.rb
restful_resource-2.5.1 lib/restful_resource/rails_validations.rb