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.



173
174
175
176
177
178
179
# File 'lib/sinatra/base.rb', line 173

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)



374
375
376
# File 'lib/sinatra/base.rb', line 374

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.



85
86
87
88
89
90
91
92
93
94
# File 'lib/sinatra/base.rb', line 85

def body(value=nil, &block)
  if block_given?
    def block.each; yield(call) end
    response.body = block
  elsif value
    response.body = value
  else
    response.body
  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



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/sinatra/base.rb', line 290

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 do |key, value|
    key = key.to_s.tr('_', '-')
    value = value.to_i if key == "max-age"
    values << [key, value].join('=')
  end

  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.



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/sinatra/base.rb', line 159

def content_type(type, params={})
  default = params.delete :default
  mime_type = mime_type(type) || default
  fail "Unknown media type: %p" % type if mime_type.nil?
  mime_type = mime_type.dup
  unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type }
    params[:charset] = params.delete('charset') || settings.default_encoding
  end
  mime_type << ";#{params.map { |kv| kv.join('=') }.join(', ')}" unless params.empty?
  response['Content-Type'] = mime_type
end

#error(code, body = nil) ⇒ Object

Halt processing and return the error status provided.



130
131
132
133
134
# File 'lib/sinatra/base.rb', line 130

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)


360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/sinatra/base.rb', line 360

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


318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/sinatra/base.rb', line 318

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

  if Integer === amount
    time    = Time.now + amount
    max_age = amount
  else
    time    = time_for amount
    max_age = time - Time.now
  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.



142
143
144
145
# File 'lib/sinatra/base.rb', line 142

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



342
343
344
345
346
347
348
349
# File 'lib/sinatra/base.rb', line 342

def last_modified(time)
  return unless time
  time = time_for time
  response['Last-Modified'] = time.httpdate
  # compare based on seconds since epoch
  halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
rescue ArgumentError
end

#mime_type(type) ⇒ Object

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



153
154
155
# File 'lib/sinatra/base.rb', line 153

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

#not_found(body = nil) ⇒ Object

Halt processing and return a 404 Not Found.



137
138
139
# File 'lib/sinatra/base.rb', line 137

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

#redirect(uri, *args) ⇒ Object

Halt processing and redirect to the URI provided.



97
98
99
100
101
102
103
104
# File 'lib/sinatra/base.rb', line 97

def redirect(uri, *args)
  status 302

  # According to RFC 2616 section 14.30, "the field value consists of a
  # single absolute URI"
  response['Location'] = url(uri, settings.absolute_redirects?, settings.prefixed_redirects?)
  halt(*args)
end

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

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



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/sinatra/base.rb', line 182

def send_file(path, opts={})
  stat = File.stat(path)
  last_modified(opts[:last_modified] || stat.mtime)

  if opts[:type] or not response['Content-Type']
    content_type opts[:type] || File.extname(path), :default => 'application/octet-stream'
  end

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

  file_length = opts[:length] || stat.size
  sf = StaticFile.open(path, 'rb')
  if ! sf.parse_ranges(env, file_length)
    response['Content-Range'] = "bytes */#{file_length}"
    halt 416
  elsif r=sf.range
    response['Content-Range'] = "bytes #{r.begin}-#{r.end}/#{file_length}"
    response['Content-Length'] = (r.end - r.begin + 1).to_s
    halt 206, sf
  else
    response['Content-Length'] ||= file_length.to_s
    halt sf
  end
rescue Errno::ENOENT
  not_found
end

#sessionObject

Access the underlying Rack session.



148
149
150
# File 'lib/sinatra/base.rb', line 148

def session
  request.session
end

#status(value = nil) ⇒ Object

Set or retrieve the response status code.



78
79
80
81
# File 'lib/sinatra/base.rb', line 78

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

#uri(addr = nil, absolute = true, add_script_name = true) ⇒ Object Also known as: url, to

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



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/sinatra/base.rb', line 108

def uri(addr = nil, absolute = true, add_script_name = true)
  return addr if addr =~ /^https?:\/\//
  uri = [host = ""]
  if absolute
    host << 'http'
    host << 's' if request.secure?
    host << "://"
    if request.forwarded? or request.port != (request.secure? ? 443 : 80)
      host << request.host_with_port
    else
      host << request.host
    end
  end
  uri << request.script_name.to_s if add_script_name
  uri << (addr ? addr : request.path_info).to_s
  File.join uri
end