lib/pragma/operation/base.rb in pragma-operation-1.1.1 vs lib/pragma/operation/base.rb in pragma-operation-1.2.0
- old
+ new
@@ -75,10 +75,11 @@
def inherited(child)
child.class_eval do
before :setup_context
around :handle_halt
after :mark_result, :consolidate_status, :validate_status, :set_default_status
+ after :build_links
end
end
# Returns the name of this operation.
#
@@ -119,23 +120,25 @@
#
# Note that calling this method doesn't halt the execution of the operation and that this
# method can be called multiple times, overriding the previous context.
#
# @param status [Integer|Symbol] an HTTP status code
- # @param headers [Hash] HTTP headers
# @param resource [Object] an object responding to +#to_json+
- def respond_with(status: nil, headers: {}, resource: nil)
- context.status = status
- context.headers = headers.to_h
- context.resource = resource
+ # @param headers [Hash] HTTP headers
+ # @param links [Hash] links to use for building the +Link+ header
+ def respond_with(status: nil, resource: nil, headers: nil, links: nil)
+ context.status = status if status
+ context.resource = resource if resource
+ context.headers = headers if headers
+ context.links = links if links
end
# Same as {#respond_with}, but also halts the execution of the operation.
#
# @see #respond_with
def respond_with!(*args)
- respond_with *args
+ respond_with(*args)
fail Halt
end
# Sets the status to respond with.
#
@@ -166,10 +169,28 @@
# @return [Object]
def current_user
context.current_user
end
+ # Returns the headers we are responding with.
+ #
+ # This is just a shortcut for +context.headers+.
+ #
+ # @return [Hash]
+ def headers
+ context.headers
+ end
+
+ # Returns the links we are responding with.
+ #
+ # This is just a shotcut for +context.links+.
+ #
+ # @return [Hash]
+ def links
+ context.links
+ end
+
private
def with_hooks
# This overrides the default behavior, which is not to run after hooks if an exception is
# raised either in +#call+ or one of the before hooks. See:
@@ -185,10 +206,11 @@
end
def setup_context
context.params ||= {}
context.headers = {}
+ context.links = {}
end
def handle_halt(interactor)
interactor.call
rescue Halt # rubocop:disable Lint/HandleExceptions
@@ -216,9 +238,21 @@
end
def mark_result
return if /\A(2|3)\d{2}\z/ =~ STATUSES.invert[context.status].to_s
context.fail!
+ end
+
+ def build_links
+ headers.delete('Link')
+
+ link_header = context.links.each_pair.select do |relation, url|
+ url && !url.empty?
+ end.map do |relation, url|
+ %(<#{url}>; rel="#{relation}")
+ end.join(",\n ")
+
+ headers['Link'] = link_header unless link_header.empty?
end
end
Halt = Class.new(StandardError)