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 139
139:     def attachment(filename=nil)
140:       response['Content-Disposition'] = 'attachment'
141:       if filename
142:         params = '; filename="%s"' % File.basename(filename)
143:         response['Content-Disposition'] << params
144:       end
145:     end

Sugar for redirect (example: redirect back)

[Source]

     # File lib/sinatra/base.rb, line 337
337:     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 69
69:     def body(value=nil, &block)
70:       if block_given?
71:         def block.each; yield(call) end
72:         response.body = block
73:       elsif value
74:         response.body = value
75:       else
76:         response.body
77:       end
78:     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 257
257:     def cache_control(*values)
258:       if values.last.kind_of?(Hash)
259:         hash = values.pop
260:         hash.reject! { |k,v| v == false }
261:         hash.reject! { |k,v| values << k if v == true }
262:       else
263:         hash = {}
264:       end
265: 
266:       values = values.map { |value| value.to_s.tr('_','-') }
267:       hash.each { |k,v| values << [k.to_s.tr('_', '-'), v].join('=') }
268: 
269:       response['Cache-Control'] = values.join(', ') if values.any?
270:     end

Set the Content-Type of the response body given a media type or file extension.

[Source]

     # File lib/sinatra/base.rb, line 130
130:     def content_type(type, params={})
131:       mime_type = mime_type(type)
132:       fail "Unknown media type: %p" % type if mime_type.nil?
133:       params[:charset] ||= params.delete('charset') || settings.default_encoding
134:       response['Content-Type'] = "#{mime_type};#{params.map { |kv| kv.join('=') }.join(', ')}"
135:     end

Halt processing and return the error status provided.

[Source]

     # File lib/sinatra/base.rb, line 101
101:     def error(code, body=nil)
102:       code, body    = 500, code.to_str if code.respond_to? :to_str
103:       response.body = body unless body.nil?
104:       halt code
105:     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 323
323:     def etag(value, kind=:strong)
324:       raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
325:       value = '"%s"' % value
326:       value = 'W/' + value if kind == :weak
327:       response['ETag'] = value
328: 
329:       # Conditional GET check
330:       if etags = env['HTTP_IF_NONE_MATCH']
331:         etags = etags.split(/\s*,\s*/)
332:         halt 304 if etags.include?(value) || etags.include?('*')
333:       end
334:     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 281
281:     def expires(amount, *values)
282:       values << {} unless values.last.kind_of?(Hash)
283: 
284:       if amount.respond_to?(:to_time)
285:         max_age = amount.to_time - Time.now
286:         time = amount.to_time
287:       else
288:         max_age = amount
289:         time = Time.now + amount
290:       end
291: 
292:       values.last.merge!(:max_age => max_age)
293:       cache_control(*values)
294: 
295:       response['Expires'] = time.httpdate
296:     end

Set multiple response headers with Hash.

[Source]

     # File lib/sinatra/base.rb, line 113
113:     def headers(hash=nil)
114:       response.headers.merge! hash if hash
115:       response.headers
116:     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 305
305:     def last_modified(time)
306:       return unless time
307:       time = time.to_time if time.respond_to?(:to_time)
308:       time = Time.parse time.strftime('%FT%T%:z') if time.respond_to?(:strftime)
309:       response['Last-Modified'] = time.respond_to?(:httpdate) ? time.httpdate : time.to_s
310:       halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']) >= time
311:     rescue ArgumentError
312:     end

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

[Source]

     # File lib/sinatra/base.rb, line 124
124:     def mime_type(type)
125:       Base.mime_type(type)
126:     end

Halt processing and return a 404 Not Found.

[Source]

     # File lib/sinatra/base.rb, line 108
108:     def not_found(body=nil)
109:       error 404, body
110:     end

Halt processing and redirect to the URI provided.

[Source]

    # File lib/sinatra/base.rb, line 81
81:     def  redirectredirect(uri, *args)
82:       if not uri =~ /^https?:\/\//
83:         # According to RFC 2616 section 14.30, "the field value consists of a
84:         # single absolute URI"
85:         abs_uri = "#{request.scheme}://#{request.host}"
86: 
87:         if request.scheme == 'https' && request.port != 443 ||
88:               request.scheme == 'http' && request.port != 80
89:           abs_uri << ":#{request.port}"
90:         end
91: 
92:         uri = (abs_uri << uri)
93:       end
94: 
95:       status 302
96:       response['Location'] = uri
97:       halt(*args)
98:     end

Use the contents of the file at path as the response body.

[Source]

     # File lib/sinatra/base.rb, line 148
148:     def send_file(path, opts={})
149:       stat = File.stat(path)
150:       last_modified stat.mtime
151: 
152:       content_type opts[:type] ||
153:         File.extname(path) ||
154:         response['Content-Type'] ||
155:         'application/octet-stream'
156: 
157:       if opts[:disposition] == 'attachment' || opts[:filename]
158:         attachment opts[:filename] || path
159:       elsif opts[:disposition] == 'inline'
160:         response['Content-Disposition'] = 'inline'
161:       end
162: 
163:       file_length = opts[:length] || stat.size
164:       sf = StaticFile.open(path, 'rb')
165:       if ! sf.parse_ranges(env, file_length)
166:         response['Content-Range'] = "bytes */#{file_length}"
167:         halt 416
168:       elsif r=sf.range
169:         response['Content-Range'] = "bytes #{r.begin}-#{r.end}/#{file_length}"
170:         response['Content-Length'] = (r.end - r.begin + 1).to_s
171:         halt 206, sf
172:       else
173:         response['Content-Length'] ||= file_length.to_s
174:         halt sf
175:       end
176:     rescue Errno::ENOENT
177:       not_found
178:     end

Access the underlying Rack session.

[Source]

     # File lib/sinatra/base.rb, line 119
119:     def session
120:       request.session
121:     end

Set or retrieve the response status code.

[Source]

    # File lib/sinatra/base.rb, line 62
62:     def status(value=nil)
63:       response.status = value if value
64:       response.status
65:     end

[Validate]