| 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 200
200: def attachment(filename=nil)
201: response['Content-Disposition'] = 'attachment'
202: if filename
203: params = '; filename="%s"' % File.basename(filename)
204: response['Content-Disposition'] << params
205: end
206: 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 107
107: def body(value=nil, &block)
108: if block_given?
109: def block.each; yield(call) end
110: response.body = block
111: elsif value
112: response.body = value
113: else
114: response.body
115: end
116: 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 317
317: def cache_control(*values)
318: if values.last.kind_of?(Hash)
319: hash = values.pop
320: hash.reject! { |k,v| v == false }
321: hash.reject! { |k,v| values << k if v == true }
322: else
323: hash = {}
324: end
325:
326: values = values.map { |value| value.to_s.tr('_','-') }
327: hash.each do |key, value|
328: key = key.to_s.tr('_', '-')
329: value = value.to_i if key == "max-age"
330: values << [key, value].join('=')
331: end
332:
333: response['Cache-Control'] = values.join(', ') if values.any?
334: end
Set the Content-Type of the response body given a media type or file extension.
# File lib/sinatra/base.rb, line 181
181: def content_type(type = nil, params={})
182: return response['Content-Type'] unless type
183: default = params.delete :default
184: mime_type = mime_type(type) || default
185: fail "Unknown media type: %p" % type if mime_type.nil?
186: mime_type = mime_type.dup
187: unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type }
188: params[:charset] = params.delete('charset') || settings.default_encoding
189: end
190: params.delete :charset if mime_type.include? 'charset'
191: unless params.empty?
192: mime_type << (mime_type.include?(';') ? ', ' : ';')
193: mime_type << params.map { |kv| kv.join('=') }.join(', ')
194: end
195: response['Content-Type'] = mime_type
196: 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 387
387: def etag(value, kind=:strong)
388: raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
389: value = '"%s"' % value
390: value = 'W/' + value if kind == :weak
391: response['ETag'] = value
392:
393: # Conditional GET check
394: if etags = env['HTTP_IF_NONE_MATCH']
395: etags = etags.split(/\s*,\s*/)
396: halt 304 if etags.include?(value) || etags.include?('*')
397: end
398: 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 345
345: def expires(amount, *values)
346: values << {} unless values.last.kind_of?(Hash)
347:
348: if Integer === amount
349: time = Time.now + amount
350: max_age = amount
351: else
352: time = time_for amount
353: max_age = time - Time.now
354: end
355:
356: values.last.merge!(:max_age => max_age)
357: cache_control(*values)
358:
359: response['Expires'] = time.httpdate
360: 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 369
369: def last_modified(time)
370: return unless time
371: time = time_for time
372: response['Last-Modified'] = time.httpdate
373: # compare based on seconds since epoch
374: halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
375: rescue ArgumentError
376: end
Look up a media type by file extension in Rack‘s mime registry.
# File lib/sinatra/base.rb, line 175
175: def mime_type(type)
176: Base.mime_type(type)
177: end
Halt processing and return a 404 Not Found.
# File lib/sinatra/base.rb, line 159
159: def not_found(body=nil)
160: error 404, body
161: end
Halt processing and redirect to the URI provided.
# File lib/sinatra/base.rb, line 119
119: def redirectredirect(uri, *args)
120: status 302
121:
122: # According to RFC 2616 section 14.30, "the field value consists of a
123: # single absolute URI"
124: response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?)
125: halt(*args)
126: end
Use the contents of the file at path as the response body.
# File lib/sinatra/base.rb, line 209
209: def send_file(path, opts={})
210: stat = File.stat(path)
211: last_modified(opts[:last_modified] || stat.mtime)
212:
213: if opts[:type] or not response['Content-Type']
214: content_type opts[:type] || File.extname(path), :default => 'application/octet-stream'
215: end
216:
217: if opts[:disposition] == 'attachment' || opts[:filename]
218: attachment opts[:filename] || path
219: elsif opts[:disposition] == 'inline'
220: response['Content-Disposition'] = 'inline'
221: end
222:
223: file_length = opts[:length] || stat.size
224: sf = StaticFile.open(path, 'rb')
225: if ! sf.parse_ranges(env, file_length)
226: response['Content-Range'] = "bytes */#{file_length}"
227: halt 416
228: elsif r=sf.range
229: response['Content-Range'] = "bytes #{r.begin}-#{r.end}/#{file_length}"
230: response['Content-Length'] = (r.end - r.begin + 1).to_s
231: halt 206, sf
232: else
233: response['Content-Length'] ||= file_length.to_s
234: halt sf
235: end
236: rescue Errno::ENOENT
237: not_found
238: end
Generates the absolute URI for a given path in the app. Takes Rack routers and reverse proxies into account.
# File lib/sinatra/base.rb, line 130
130: def uri(addr = nil, absolute = true, add_script_name = true)
131: return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/
132: uri = [host = ""]
133: if absolute
134: host << 'http'
135: host << 's' if request.secure?
136: host << "://"
137: if request.forwarded? or request.port != (request.secure? ? 443 : 80)
138: host << request.host_with_port
139: else
140: host << request.host
141: end
142: end
143: uri << request.script_name.to_s if add_script_name
144: uri << (addr ? addr : request.path_info).to_s
145: File.join uri
146: end