Module | Sinatra::Helpers |
In: |
lib/sinatra/base.rb
|
Methods available to routes, before/after filters, and views.
Set the Content-Disposition to "attachment" with the specified filename, instructing the user agents to prompt to save.
# File lib/sinatra/base.rb, line 156 156: def attachment(filename=nil) 157: response['Content-Disposition'] = 'attachment' 158: if filename 159: params = '; filename="%s"' % File.basename(filename) 160: response['Content-Disposition'] << params 161: end 162: end
Set or retrieve the response body. When a block is given, evaluation is deferred until the body is read with each.
# File lib/sinatra/base.rb, line 81 81: def body(value=nil, &block) 82: if block_given? 83: def block.each; yield(call) end 84: response.body = block 85: elsif value 86: response.body = value 87: else 88: response.body 89: end 90: end
Specify response freshness policy for HTTP caches (Cache-Control header). Any number of non-value directives (:public, :private, :no_cache, :no_store, :must_revalidate, :proxy_revalidate) may be passed along with a Hash of value directives (:max_age, :min_stale, :s_max_age).
cache_control :public, :must_revalidate, :max_age => 60 => Cache-Control: public, must-revalidate, max-age=60
See RFC 2616 / 14.9 for more on standard cache control directives: tools.ietf.org/html/rfc2616#section-14.9.1
# File lib/sinatra/base.rb, line 273 273: def cache_control(*values) 274: if values.last.kind_of?(Hash) 275: hash = values.pop 276: hash.reject! { |k,v| v == false } 277: hash.reject! { |k,v| values << k if v == true } 278: else 279: hash = {} 280: end 281: 282: values = values.map { |value| value.to_s.tr('_','-') } 283: hash.each do |key, value| 284: key = key.to_s.tr('_', '-') 285: value = value.to_i if key == "max-age" 286: values << [key, value].join('=') 287: end 288: 289: response['Cache-Control'] = values.join(', ') if values.any? 290: end
Set the Content-Type of the response body given a media type or file extension.
# File lib/sinatra/base.rb, line 142 142: def content_type(type, params={}) 143: default = params.delete :default 144: mime_type = mime_type(type) || default 145: fail "Unknown media type: %p" % type if mime_type.nil? 146: mime_type = mime_type.dup 147: unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } 148: params[:charset] = params.delete('charset') || settings.default_encoding 149: end 150: mime_type << ";#{params.map { |kv| kv.join('=') }.join(', ')}" unless params.empty? 151: response['Content-Type'] = mime_type 152: end
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.
# File lib/sinatra/base.rb, line 350 350: def etag(value, kind=:strong) 351: raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind) 352: value = '"%s"' % value 353: value = 'W/' + value if kind == :weak 354: response['ETag'] = value 355: 356: # Conditional GET check 357: if etags = env['HTTP_IF_NONE_MATCH'] 358: etags = etags.split(/\s*,\s*/) 359: halt 304 if etags.include?(value) || etags.include?('*') 360: end 361: end
Set the Expires header and Cache-Control/max-age directive. Amount can be an integer number of seconds in the future or a Time object indicating when the response should be considered "stale". The remaining "values" arguments are passed to the cache_control helper:
expires 500, :public, :must_revalidate => Cache-Control: public, must-revalidate, max-age=60 => Expires: Mon, 08 Jun 2009 08:50:17 GMT
# File lib/sinatra/base.rb, line 301 301: def expires(amount, *values) 302: values << {} unless values.last.kind_of?(Hash) 303: 304: if amount.respond_to?(:to_time) 305: max_age = amount.to_time - Time.now 306: time = amount.to_time 307: else 308: max_age = amount 309: time = Time.now + amount 310: end 311: 312: values.last.merge!(:max_age => max_age) 313: cache_control(*values) 314: 315: response['Expires'] = time.httpdate 316: end
Set the last modified time of the resource (HTTP ‘Last-Modified’ header) and halt if conditional GET matches. The time argument is a Time, DateTime, or other object that responds to to_time.
When the current request includes an ‘If-Modified-Since’ header that is equal or later than the time specified, execution is immediately halted with a ‘304 Not Modified’ response.
# File lib/sinatra/base.rb, line 325 325: def last_modified(time) 326: return unless time 327: if time.respond_to?(:to_time) 328: time = time.to_time 329: else 330: ## make a best effort to convert something else to a time object 331: ## if this fails, this should throw an ArgumentError, then the 332: # rescue will result in an http 200, which should be safe 333: time = Time.parse(time.to_s) 334: end 335: response['Last-Modified'] = time.httpdate 336: # compare based on seconds since epoch 337: halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i 338: rescue ArgumentError 339: end
Look up a media type by file extension in Rack‘s mime registry.
# File lib/sinatra/base.rb, line 136 136: def mime_type(type) 137: Base.mime_type(type) 138: end
Halt processing and return a 404 Not Found.
# File lib/sinatra/base.rb, line 120 120: def not_found(body=nil) 121: error 404, body 122: end
Halt processing and redirect to the URI provided.
# File lib/sinatra/base.rb, line 93 93: def redirectredirect(uri, *args) 94: if not uri =~ /^https?:\/\// 95: # According to RFC 2616 section 14.30, "the field value consists of a 96: # single absolute URI" 97: abs_uri = "#{request.scheme}://#{request.host}" 98: 99: if request.scheme == 'https' && request.port != 443 || 100: request.scheme == 'http' && request.port != 80 101: abs_uri << ":#{request.port}" 102: end 103: 104: uri = (abs_uri << uri) 105: end 106: 107: status 302 108: response['Location'] = uri 109: halt(*args) 110: end
Use the contents of the file at path as the response body.
# File lib/sinatra/base.rb, line 165 165: def send_file(path, opts={}) 166: stat = File.stat(path) 167: last_modified stat.mtime 168: 169: if opts[:type] or not response['Content-Type'] 170: content_type opts[:type] || File.extname(path), :default => 'application/octet-stream' 171: end 172: 173: if opts[:disposition] == 'attachment' || opts[:filename] 174: attachment opts[:filename] || path 175: elsif opts[:disposition] == 'inline' 176: response['Content-Disposition'] = 'inline' 177: end 178: 179: file_length = opts[:length] || stat.size 180: sf = StaticFile.open(path, 'rb') 181: if ! sf.parse_ranges(env, file_length) 182: response['Content-Range'] = "bytes */#{file_length}" 183: halt 416 184: elsif r=sf.range 185: response['Content-Range'] = "bytes #{r.begin}-#{r.end}/#{file_length}" 186: response['Content-Length'] = (r.end - r.begin + 1).to_s 187: halt 206, sf 188: else 189: response['Content-Length'] ||= file_length.to_s 190: halt sf 191: end 192: rescue Errno::ENOENT 193: not_found 194: end