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