Sha256: 2f9984e06ffeec8b4c15caf8957160c6a87ee2e1ab1245bf72fb0b43b7a8650b

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

module RestfulResource
  module RailsValidations
    module ClassMethods
      def put(id, data: {}, **params)
        begin
          super(id, data: data, **params)
        rescue HttpClient::UnprocessableEntity => e
          errors = parse_json(e.response.body)
          result = nil
          if errors.is_a?(Hash) && errors.has_key?('errors')
            result = data.merge(errors)
          else
            result = data.merge(errors: errors)
          end
          result = result.merge(id: id)
          self.new(result)
        end
      end

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

      def get(params = {})
        with_validations do
          super(params)
        end
      end

      private
      def with_validations(data: {}, &block)
        begin
          block.call
        rescue HttpClient::UnprocessableEntity => e
          errors = parse_json(e.response.body)
          result = nil
          if errors.is_a?(Hash) && errors.has_key?('errors')
            result = data.merge(errors)
          else
            result = data.merge(errors: errors)
          end
          self.new(result)
        end
      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-1.6.0 lib/restful_resource/rails_validations.rb
restful_resource-1.5.0 lib/restful_resource/rails_validations.rb
restful_resource-1.4.3 lib/restful_resource/rails_validations.rb
restful_resource-1.4.2 lib/restful_resource/rails_validations.rb
restful_resource-1.4.1 lib/restful_resource/rails_validations.rb
restful_resource-1.4.0 lib/restful_resource/rails_validations.rb