Sha256: bce4acefd0f6a6a47878ad1996dc560ba9d1e9e9c5c881e27712dd2f85b49290

Contents?: true

Size: 1.16 KB

Versions: 2

Compression:

Stored size: 1.16 KB

Contents

module RestfulResource
  module RailsValidations
    module ClassMethods
      def put(id, data: {}, **)
        super
      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)
        new(result)
      end

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

      def get(*)
        with_validations { super }
      end

      private

      def with_validations(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
        new(result)
      end
    end

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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
restful_resource-2.5.0 lib/restful_resource/rails_validations.rb
restful_resource-2.4.0 lib/restful_resource/rails_validations.rb