Module: Sinatra::Helpers

Included in:
Base
Defined in:
lib/sinatra/base.rb

Overview

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

Defined Under Namespace

Classes: StaticFile

Instance Method Summary collapse

Instance Method Details

#attachment(filename = nil) ⇒ Object

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



137
138
139
140
141
142
143
# File 'lib/sinatra/base.rb', line 137

def attachment(filename=nil)
  response['Content-Disposition'] = 'attachment'
  if filename
    params = '; filename="%s"' % File.basename(filename)
    response['Content-Disposition'] << params
  end
end

#backObject

Sugar for redirect (example: redirect back)



269
# File 'lib/sinatra/base.rb', line 269

def back ; request.referer ; end

#body(value = nil, &block) ⇒ Object

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



78
79
80
81
82
83
84
85
# File 'lib/sinatra/base.rb', line 78

def body(value=nil, &block)
  if block_given?
    def block.each ; yield call ; end
    response.body = block
  else
    response.body = value
  end
end

#cache_control(*values) ⇒ Object

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



190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/sinatra/base.rb', line 190

def cache_control(*values)
  if values.last.kind_of?(Hash)
    hash = values.pop
    hash.reject! { |k,v| v == false }
    hash.reject! { |k,v| values << k if v == true }
  else
    hash = {}
  end

  values = values.map { |value| value.to_s.tr('_','-') }
  hash.each { |k,v| values << [k.to_s.tr('_', '-'), v].join('=') }

  response['Cache-Control'] = values.join(', ') if values.any?
end

#content_type(type, params = {}) ⇒ Object

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



124
125
126
127
128
129
130
131
132
133
# File 'lib/sinatra/base.rb', line 124

def content_type(type, params={})
  mime_type = self.mime_type(type)
  fail "Unknown media type: %p" % type if mime_type.nil?
  if params.any?
    params = params.collect { |kv| "%s=%s" % kv }.join(', ')
    response['Content-Type'] = [mime_type, params].join(";")
  else
    response['Content-Type'] = mime_type
  end
end

#error(code, body = nil) ⇒ Object

Halt processing and return the error status provided.



95
96
97
98
99
# File 'lib/sinatra/base.rb', line 95

def error(code, body=nil)
  code, body    = 500, code.to_str if code.respond_to? :to_str
  response.body = body unless body.nil?
  halt code
end

#etag(value, kind = :strong) ⇒ Object

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.

Raises:

  • (TypeError)


255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/sinatra/base.rb', line 255

def etag(value, kind=:strong)
  raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
  value = '"%s"' % value
  value = 'W/' + value if kind == :weak
  response['ETag'] = value

  # Conditional GET check
  if etags = env['HTTP_IF_NONE_MATCH']
    etags = etags.split(/\s*,\s*/)
    halt 304 if etags.include?(value) || etags.include?('*')
  end
end

#expires(amount, *values) ⇒ Object

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


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/sinatra/base.rb', line 214

def expires(amount, *values)
  values << {} unless values.last.kind_of?(Hash)

  if amount.respond_to?(:to_time)
    max_age = amount.to_time - Time.now
    time = amount.to_time
  else
    max_age = amount
    time = Time.now + amount
  end

  values.last.merge!(:max_age => max_age)
  cache_control(*values)

  response['Expires'] = time.httpdate
end

#headers(hash = nil) ⇒ Object

Set multiple response headers with Hash.



107
108
109
110
# File 'lib/sinatra/base.rb', line 107

def headers(hash=nil)
  response.headers.merge! hash if hash
  response.headers
end

#last_modified(time) ⇒ Object

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 matches the time specified, execution is immediately halted with a ‘304 Not Modified’ response.



238
239
240
241
242
243
244
# File 'lib/sinatra/base.rb', line 238

def last_modified(time)
  time = time.to_time if time.respond_to?(:to_time)
  time = time.httpdate if time.respond_to?(:httpdate)
  response['Last-Modified'] = time
  halt 304 if time == request.env['HTTP_IF_MODIFIED_SINCE']
  time
end

#mime_type(type) ⇒ Object

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



118
119
120
# File 'lib/sinatra/base.rb', line 118

def mime_type(type)
  Base.mime_type(type)
end

#not_found(body = nil) ⇒ Object

Halt processing and return a 404 Not Found.



102
103
104
# File 'lib/sinatra/base.rb', line 102

def not_found(body=nil)
  error 404, body
end

#redirect(uri, *args) ⇒ Object

Halt processing and redirect to the URI provided.



88
89
90
91
92
# File 'lib/sinatra/base.rb', line 88

def redirect(uri, *args)
  status 302
  response['Location'] = uri
  halt(*args)
end

#send_file(path, opts = {}) ⇒ Object

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



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/sinatra/base.rb', line 146

def send_file(path, opts={})
  stat = File.stat(path)
  last_modified stat.mtime

  content_type mime_type(opts[:type]) ||
    mime_type(File.extname(path)) ||
    response['Content-Type'] ||
    'application/octet-stream'

  response['Content-Length'] ||= (opts[:length] || stat.size).to_s

  if opts[:disposition] == 'attachment' || opts[:filename]
    attachment opts[:filename] || path
  elsif opts[:disposition] == 'inline'
    response['Content-Disposition'] = 'inline'
  end

  halt StaticFile.open(path, 'rb')
rescue Errno::ENOENT
  not_found
end

#sessionObject

Access the underlying Rack session.



113
114
115
# File 'lib/sinatra/base.rb', line 113

def session
  env['rack.session'] ||= {}
end

#status(value = nil) ⇒ Object

Set or retrieve the response status code.



71
72
73
74
# File 'lib/sinatra/base.rb', line 71

def status(value=nil)
  response.status = value if value
  response.status
end