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

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

Methods

attachment   back   body   cache_control   content_type   error   etag   expires   headers   last_modified   mime_type   not_found   redirect   send_file   session   status   to   uri   url  

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 196
196:     def attachment(filename=nil)
197:       response['Content-Disposition'] = 'attachment'
198:       if filename
199:         params = '; filename="%s"' % File.basename(filename)
200:         response['Content-Disposition'] << params
201:       end
202:     end

Sugar for redirect (example: redirect back)

[Source]

     # File lib/sinatra/base.rb, line 397
397:     def back
398:       request.referer
399:     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 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

[Source]

     # File lib/sinatra/base.rb, line 313
313:     def cache_control(*values)
314:       if values.last.kind_of?(Hash)
315:         hash = values.pop
316:         hash.reject! { |k,v| v == false }
317:         hash.reject! { |k,v| values << k if v == true }
318:       else
319:         hash = {}
320:       end
321: 
322:       values = values.map { |value| value.to_s.tr('_','-') }
323:       hash.each do |key, value|
324:         key = key.to_s.tr('_', '-')
325:         value = value.to_i if key == "max-age"
326:         values << [key, value].join('=')
327:       end
328: 
329:       response['Cache-Control'] = values.join(', ') if values.any?
330:     end

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

[Source]

     # File lib/sinatra/base.rb, line 177
177:     def content_type(type = nil, params={})
178:       return response['Content-Type'] unless type
179:       default = params.delete :default
180:       mime_type = mime_type(type) || default
181:       fail "Unknown media type: %p" % type if mime_type.nil?
182:       mime_type = mime_type.dup
183:       unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type }
184:         params[:charset] = params.delete('charset') || settings.default_encoding
185:       end
186:       params.delete :charset if mime_type.include? 'charset'
187:       unless params.empty?
188:         mime_type << (mime_type.include?(';') ? ', ' : ';')
189:         mime_type << params.map { |kv| kv.join('=') }.join(', ')
190:       end
191:       response['Content-Type'] = mime_type
192:     end

Halt processing and return the error status provided.

[Source]

     # File lib/sinatra/base.rb, line 148
148:     def error(code, body=nil)
149:       code, body    = 500, code.to_str if code.respond_to? :to_str
150:       response.body = body unless body.nil?
151:       halt code
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.

[Source]

     # File lib/sinatra/base.rb, line 383
383:     def etag(value, kind=:strong)
384:       raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
385:       value = '"%s"' % value
386:       value = 'W/' + value if kind == :weak
387:       response['ETag'] = value
388: 
389:       # Conditional GET check
390:       if etags = env['HTTP_IF_NONE_MATCH']
391:         etags = etags.split(/\s*,\s*/)
392:         halt 304 if etags.include?(value) || etags.include?('*')
393:       end
394:     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 341
341:     def expires(amount, *values)
342:       values << {} unless values.last.kind_of?(Hash)
343: 
344:       if amount.is_a? Integer
345:         time    = Time.now + amount.to_i
346:         max_age = amount
347:       else
348:         time    = time_for amount
349:         max_age = time - Time.now
350:       end
351: 
352:       values.last.merge!(:max_age => max_age)
353:       cache_control(*values)
354: 
355:       response['Expires'] = time.httpdate
356:     end

Set multiple response headers with Hash.

[Source]

     # File lib/sinatra/base.rb, line 160
160:     def headers(hash=nil)
161:       response.headers.merge! hash if hash
162:       response.headers
163:     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 365
365:     def last_modified(time)
366:       return unless time
367:       time = time_for time
368:       response['Last-Modified'] = time.httpdate
369:       # compare based on seconds since epoch
370:       halt 304 if Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
371:     rescue ArgumentError
372:     end

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

[Source]

     # File lib/sinatra/base.rb, line 171
171:     def mime_type(type)
172:       Base.mime_type(type)
173:     end

Halt processing and return a 404 Not Found.

[Source]

     # File lib/sinatra/base.rb, line 155
155:     def not_found(body=nil)
156:       error 404, body
157:     end

Halt processing and redirect to the URI provided.

[Source]

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

[Source]

     # File lib/sinatra/base.rb, line 205
205:     def send_file(path, opts={})
206:       stat = File.stat(path)
207:       last_modified(opts[:last_modified] || stat.mtime)
208: 
209:       if opts[:type] or not response['Content-Type']
210:         content_type opts[:type] || File.extname(path), :default => 'application/octet-stream'
211:       end
212: 
213:       if opts[:disposition] == 'attachment' || opts[:filename]
214:         attachment opts[:filename] || path
215:       elsif opts[:disposition] == 'inline'
216:         response['Content-Disposition'] = 'inline'
217:       end
218: 
219:       file_length = opts[:length] || stat.size
220:       sf = StaticFile.open(path, 'rb')
221:       if ! sf.parse_ranges(env, file_length)
222:         response['Content-Range'] = "bytes */#{file_length}"
223:         halt 416
224:       elsif r=sf.range
225:         response['Content-Range'] = "bytes #{r.begin}-#{r.end}/#{file_length}"
226:         response['Content-Length'] = (r.end - r.begin + 1).to_s
227:         halt 206, sf
228:       else
229:         response['Content-Length'] ||= file_length.to_s
230:         halt sf
231:       end
232:     rescue Errno::ENOENT
233:       not_found
234:     end

Access the underlying Rack session.

[Source]

     # File lib/sinatra/base.rb, line 166
166:     def session
167:       request.session
168:     end

Set or retrieve the response status code.

[Source]

    # File lib/sinatra/base.rb, line 96
96:     def status(value=nil)
97:       response.status = value if value
98:       response.status
99:     end
to(addr = nil, absolute = true, add_script_name = true)

Alias for uri

Generates the absolute URI for a given path in the app. Takes Rack routers and reverse proxies into account.

[Source]

     # 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'
131:         host << 's' if request.secure?
132:         host << "://"
133:         if request.forwarded? or request.port != (request.secure? ? 443 : 80)
134:           host << request.host_with_port
135:         else
136:           host << request.host
137:         end
138:       end
139:       uri << request.script_name.to_s if add_script_name
140:       uri << (addr ? addr : request.path_info).to_s
141:       File.join uri
142:     end
url(addr = nil, absolute = true, add_script_name = true)

Alias for uri

[Validate]