Module Sinatra::Helpers
In: lib/sinatra/base.rb

Methods available to routes, before/after filters, and views.

Methods

Public Instance methods

Set the Content-Disposition to "attachment" with the specified filename, instructing the user agents to prompt to save.

[Source]

     # 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

Sugar for redirect (example: redirect back)

[Source]

     # File lib/sinatra/base.rb, line 357
357:     def back ; request.referer ; end

Set or retrieve the response body. When a block is given, evaluation is deferred until the body is read with each.

[Source]

    # 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

[Source]

     # 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.

[Source]

     # 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

Halt processing and return the error status provided.

[Source]

     # File lib/sinatra/base.rb, line 113
113:     def error(code, body=nil)
114:       code, body    = 500, code.to_str if code.respond_to? :to_str
115:       response.body = body unless body.nil?
116:       halt code
117:     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.

[Source]

     # File lib/sinatra/base.rb, line 343
343:     def etag(value, kind=:strong)
344:       raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
345:       value = '"%s"' % value
346:       value = 'W/' + value if kind == :weak
347:       response['ETag'] = value
348: 
349:       # Conditional GET check
350:       if etags = env['HTTP_IF_NONE_MATCH']
351:         etags = etags.split(/\s*,\s*/)
352:         halt 304 if etags.include?(value) || etags.include?('*')
353:       end
354:     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

[Source]

     # 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 multiple response headers with Hash.

[Source]

     # File lib/sinatra/base.rb, line 125
125:     def headers(hash=nil)
126:       response.headers.merge! hash if hash
127:       response.headers
128:     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.

[Source]

     # File lib/sinatra/base.rb, line 325
325:     def last_modified(time)
326:       return unless time
327:       time = time.to_time if time.respond_to?(:to_time)
328:       time = Time.parse time.strftime('%FT%T%:z') if time.respond_to?(:strftime)
329:       response['Last-Modified'] = time.respond_to?(:httpdate) ? time.httpdate : time.to_s
330:       halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']) >= time
331:     rescue ArgumentError
332:     end

Look up a media type by file extension in Rack‘s mime registry.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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

Access the underlying Rack session.

[Source]

     # File lib/sinatra/base.rb, line 131
131:     def session
132:       request.session
133:     end

Set or retrieve the response status code.

[Source]

    # File lib/sinatra/base.rb, line 74
74:     def status(value=nil)
75:       response.status = value if value
76:       response.status
77:     end

[Validate]