lib/shamu/json_api/response.rb in shamu-0.0.4 vs lib/shamu/json_api/response.rb in shamu-0.0.5
- old
+ new
@@ -32,35 +32,54 @@
build_resource resource, presenter, &block
end
self
end
- # @overload error( exception, http_status = nil )
+ # @overload error( exception )
# @param (see ErrorBuilder#exception)
# @overload error( &block )
# @yield (builder)
# @yieldparam [ErrorBuilder] builder used to describe the error.
#
# @return [self]
- def error( exception = nil, http_status = nil, &block )
+ def error( error = nil, &block )
builder = ErrorBuilder.new
- if block_given?
- yield builder
- elsif exception.is_a?( Exception )
- builder.exception( exception, http_status )
- else
- http_status ||= 500
- builder.summary http_status, http_status.to_s, exception
+ if error.is_a?( Exception )
+ builder.exception( error )
+ elsif error
+ builder.title error
end
+ yield builder if block_given?
+
errors = ( output[:errors] ||= [] )
errors << builder.compile
self
end
+ # Write ActiveModel validation errors to the response.
+ #
+ # @param [Hash<Symbol,String>] errors map of attributes to errors.
+ # @yield ( builder, attr, message )
+ # @yieldparam [ErrorBuilder] builder the builder for this error message.
+ # @yieldparam [String] attr the attribute with a validation error.
+ # @yieldparam [String] message the error message.
+ # @return [self]
+ def validation_errors( errors, &block )
+ errors.each do |attr, message|
+ error message do |builder|
+ path = "/data"
+ path << "/attributes/#{ attr }" unless attr == :base
+ builder.pointer path
+
+ yield builder, attr, message if block_given?
+ end
+ end
+ end
+
# (see BaseBuilder#compile)
def compile
@compiled ||= begin
compiled = output.dup
compiled[:jsonapi] = { version: "1.0" }
@@ -93,20 +112,18 @@
# @return [String]
def to_s
to_json
end
- # Responses don't have identifiers
- undef :identifier
-
private
def build_resource( resource, presenter, &block )
presenter = context.find_presenter( resource ) if !presenter && !block_given?
+ builder = ResourceBuilder.new( context )
- builder = ResourceBuilder.new( context )
if presenter
- presenter.present( resource, builder )
+ instance = presenter.new( resource, builder )
+ instance.present
else
yield builder
end
builder.compile
\ No newline at end of file