Sha256: f276f9738e04d76c826fe93ef15cda114bf57562aa89dab160fdf74d18cf0fed

Contents?: true

Size: 1.48 KB

Versions: 9

Compression:

Stored size: 1.48 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.to_json, given_options
          end

          # @visibility private
          def display_errors
            controller.render format => controller.json_validation_errors( resource_errors ).to_json,
                              :status => :unprocessable_entity
          end

        private

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

      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
shamu-0.0.24 lib/shamu/json_api/rails/responder.rb
shamu-0.0.21 lib/shamu/json_api/rails/responder.rb
shamu-0.0.20 lib/shamu/json_api/rails/responder.rb
shamu-0.0.19 lib/shamu/json_api/rails/responder.rb
shamu-0.0.18 lib/shamu/json_api/rails/responder.rb
shamu-0.0.17 lib/shamu/json_api/rails/responder.rb
shamu-0.0.15 lib/shamu/json_api/rails/responder.rb
shamu-0.0.14 lib/shamu/json_api/rails/responder.rb
shamu-0.0.13 lib/shamu/json_api/rails/responder.rb