Sha256: 174ae7eff6b8174dcc9defc0028b1e8faac15f79aeda2b39ab15a8c96f243328

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module Shamu
  module JsonApi
    module Rails

      # Support JSON API responses with the standard rails `#respond_with` method.
      module Responder

        # Render the response as JSON
        # @return [String]
        def to_json
          if has_errors?
            display_errors
          elsif get?
            display resource
          elsif put? || patch?
            display resource, :location => api_location
          elsif post?
            display resource, :status => :created, :location => api_location
          else
            head :no_content
          end
        end
        alias_method :to_json_api, :to_json

        protected

          # @visibility private
          def display( resource, given_options = {} )
            given_options.merge!( options )

            json =
              if resource.is_a?( Enumerable )
                controller.json_collection resource, **given_options
              else
                controller.json_resource resource, **given_options
              end

            super json, given_options
          end

          # @visibility private
          def display_errors
            controller.render format => controller.json_validation_errors( resource_errors ), :status => :unprocessable_entity # rubocop:disable Metrics/LineLength
          end

        private

          def validation_resource?( resource )
            resource.respond_to?( :valid? ) && resource.respond_to?( :errors )
          end

      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shamu-0.0.11 lib/shamu/json_api/rails/responder.rb
shamu-0.0.9 lib/shamu/json_api/rails/responder.rb
shamu-0.0.8 lib/shamu/json_api/rails/responder.rb