Method: Sinatra::Helpers#etag

Defined in:
lib/sinatra/base.rb

#etag(value, options = {}) ⇒ Object

Set the response entity tag (HTTP 'ETag' header) and halt if conditional GET matches. The +value+ argument is an identifier that uniquely identifies the current version of the resource. The +kind+ argument indicates whether the etag should be used as a :strong (default) or :weak cache validator.

When the current request includes an 'If-None-Match' header with a matching etag, execution is immediately halted. If the request method is GET or HEAD, a '304 Not Modified' response is sent.



620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/sinatra/base.rb', line 620

def etag(value, options = {})
  # Before touching this code, please double check RFC 2616 14.24 and 14.26.
  options      = { kind: options } unless Hash === options
  kind         = options[:kind] || :strong
  new_resource = options.fetch(:new_resource) { request.post? }

  unless ETAG_KINDS.include?(kind)
    raise ArgumentError, ':strong or :weak expected'
  end

  value = format('"%s"', value)
  value = "W/#{value}" if kind == :weak
  response['ETag'] = value

  return unless success? || status == 304

  if etag_matches?(env['HTTP_IF_NONE_MATCH'], new_resource)
    halt(request.safe? ? 304 : 412)
  end

  if env['HTTP_IF_MATCH']
    return if etag_matches?(env['HTTP_IF_MATCH'], new_resource)

    halt 412
  end

  nil
end