Module: Aldebaran::Helpers
- Included in:
- Base
- Defined in:
- lib/aldebaran/base.rb
Overview
Methods available to routes, before/after filters, and views.
Defined Under Namespace
Classes: Stream
Instance Method Summary (collapse)
-
- (Object) attachment(filename = nil)
Set the Content-Disposition to "attachment" with the specified filename, instructing the user agents to prompt to save.
-
- (Object) back
Sugar for redirect (example: redirect back).
-
- (Object) body(value = nil, &block)
Set or retrieve the response body.
-
- (Object) cache_control(*values)
Specify response freshness policy for HTTP caches (Cache-Control header).
-
- (Boolean) client_error?
whether or not the status is set to 4xx.
-
- (Object) content_type(type = nil, params = {})
Set the Content-Type of the response body given a media type or file extension.
-
- (Object) error(code, body = nil)
Halt processing and return the error status provided.
-
- (Object) etag(value, kind = :strong)
Set the response entity tag (HTTP 'ETag' header) and halt if conditional GET matches.
-
- (Object) expires(amount, *values)
Set the Expires header and Cache-Control/max-age directive.
-
- (Object) headers(hash = nil)
Set multiple response headers with Hash.
-
- (Boolean) informational?
whether or not the status is set to 1xx.
-
- (Object) last_modified(time)
Set the last modified time of the resource (HTTP 'Last-Modified' header) and halt if conditional GET matches.
-
- (Object) logger
Access shared logger object.
-
- (Object) mime_type(type)
Look up a media type by file extension in Rack's mime registry.
-
- (Object) not_found(body = nil)
Halt processing and return a 404 Not Found.
-
- (Boolean) not_found?
whether or not the status is set to 404.
-
- (Object) redirect(uri, *args)
Halt processing and redirect to the URI provided.
-
- (Boolean) redirect?
whether or not the status is set to 3xx.
-
- (Object) send_file(path, opts = {})
Use the contents of the file at path as the response body.
-
- (Boolean) server_error?
whether or not the status is set to 5xx.
-
- (Object) session
Access the underlying Rack session.
-
- (Object) status(value = nil)
Set or retrieve the response status code.
-
- (Object) stream(close = true, &block)
Allows to start sending data to the client even though later parts of the response body have not yet been generated.
-
- (Boolean) success?
whether or not the status is set to 2xx.
-
- (Object) time_for(value)
Generates a Time object from the given value.
-
- (Object) uri(addr = nil, absolute = true, add_script_name = true)
(also: #url, #to)
Generates the absolute URI for a given path in the app.
Instance Method Details
- (Object) attachment(filename = nil)
Set the Content-Disposition to "attachment" with the specified filename, instructing the user agents to prompt to save.
203 204 205 206 207 208 209 210 211 |
# File 'lib/aldebaran/base.rb', line 203 def (filename=nil) response['Content-Disposition'] = 'attachment' if filename params = '; filename="%s"' % File.basename(filename) response['Content-Disposition'] << params ext = File.extname(filename) content_type(ext) unless response['Content-Type'] or ext.empty? end end |
- (Object) back
Sugar for redirect (example: redirect back)
388 389 390 |
# File 'lib/aldebaran/base.rb', line 388 def back request.referer end |
- (Object) body(value = nil, &block)
Set or retrieve the response body. When a block is given, evaluation is deferred until the body is read with #each.
103 104 105 106 107 108 109 110 111 112 |
# File 'lib/aldebaran/base.rb', line 103 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 |
- (Object) cache_control(*values)
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
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/aldebaran/base.rb', line 301 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 |
- (Boolean) client_error?
whether or not the status is set to 4xx
408 409 410 |
# File 'lib/aldebaran/base.rb', line 408 def client_error? status.between? 400, 499 end |
- (Object) content_type(type = nil, params = {})
Set the Content-Type of the response body given a media type or file extension.
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/aldebaran/base.rb', line 184 def content_type(type = nil, params={}) return response['Content-Type'] unless type 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 params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << (mime_type.include?(';') ? ', ' : ';') mime_type << params.map { |kv| kv.join('=') }.join(', ') end response['Content-Type'] = mime_type end |
- (Object) error(code, body = nil)
Halt processing and return the error status provided.
150 151 152 153 154 |
# File 'lib/aldebaran/base.rb', line 150 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 |
- (Object) etag(value, kind = :strong)
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.
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/aldebaran/base.rb', line 371 def etag(value, kind = :strong) raise ArgumentError, ":strong or :weak expected" unless [:strong,:weak].include?(kind) value = '"%s"' % value value = 'W/' + value if kind == :weak response['ETag'] = value if = env['HTTP_IF_NONE_MATCH'] = .split(/\s*,\s*/) if .include?(value) or .include?('*') halt 304 if request.safe? else halt 412 unless request.safe? end end end |
- (Object) expires(amount, *values)
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
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/aldebaran/base.rb', line 329 def expires(amount, *values) values << {} unless values.last.kind_of?(Hash) if amount.is_a? Integer time = Time.now + amount.to_i 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 |
- (Object) headers(hash = nil)
Set multiple response headers with Hash.
162 163 164 165 |
# File 'lib/aldebaran/base.rb', line 162 def headers(hash=nil) response.headers.merge! hash if hash response.headers end |
- (Boolean) informational?
whether or not the status is set to 1xx
393 394 395 |
# File 'lib/aldebaran/base.rb', line 393 def informational? status.between? 100, 199 end |
- (Object) last_modified(time)
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.
353 354 355 356 357 358 359 360 |
# File 'lib/aldebaran/base.rb', line 353 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(env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i rescue ArgumentError end |
- (Object) logger
Access shared logger object.
173 174 175 |
# File 'lib/aldebaran/base.rb', line 173 def logger request.logger end |
- (Object) mime_type(type)
Look up a media type by file extension in Rack's mime registry.
178 179 180 |
# File 'lib/aldebaran/base.rb', line 178 def mime_type(type) Base.mime_type(type) end |
- (Object) not_found(body = nil)
Halt processing and return a 404 Not Found.
157 158 159 |
# File 'lib/aldebaran/base.rb', line 157 def not_found(body=nil) error 404, body end |
- (Boolean) not_found?
whether or not the status is set to 404
418 419 420 |
# File 'lib/aldebaran/base.rb', line 418 def not_found? status == 404 end |
- (Object) redirect(uri, *args)
Halt processing and redirect to the URI provided.
115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/aldebaran/base.rb', line 115 def redirect(uri, *args) if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end |
- (Boolean) redirect?
whether or not the status is set to 3xx
403 404 405 |
# File 'lib/aldebaran/base.rb', line 403 def redirect? status.between? 300, 399 end |
- (Object) send_file(path, opts = {})
Use the contents of the file at path as the response body.
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/aldebaran/base.rb', line 214 def send_file(path, opts={}) 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] opts[:filename] || path elsif opts[:disposition] == 'inline' response['Content-Disposition'] = 'inline' end last_modified opts[:last_modified] if opts[:last_modified] file = Rack::File.new nil file.path = path result = file.serving env result[1].each { |k,v| headers[k] ||= v } halt result[0], result[2] rescue Errno::ENOENT not_found end |
- (Boolean) server_error?
whether or not the status is set to 5xx
413 414 415 |
# File 'lib/aldebaran/base.rb', line 413 def server_error? status.between? 500, 599 end |
- (Object) session
Access the underlying Rack session.
168 169 170 |
# File 'lib/aldebaran/base.rb', line 168 def session request.session end |
- (Object) status(value = nil)
Set or retrieve the response status code.
96 97 98 99 |
# File 'lib/aldebaran/base.rb', line 96 def status(value=nil) response.status = value if value response.status end |
- (Object) stream(close = true, &block)
Allows to start sending data to the client even though later parts of the response body have not yet been generated.
The close parameter specifies whether Stream#close should be called after the block has been executed. This is only relevant for evented servers like Thin or Rainbows.
286 287 288 289 |
# File 'lib/aldebaran/base.rb', line 286 def stream(close = true, &block) scheduler = env['async.callback'] ? EventMachine : Stream body Stream.new(scheduler, close, &block) end |
- (Boolean) success?
whether or not the status is set to 2xx
398 399 400 |
# File 'lib/aldebaran/base.rb', line 398 def success? status.between? 200, 299 end |
- (Object) time_for(value)
Generates a Time object from the given value. Used by #expires and #last_modified.
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/aldebaran/base.rb', line 424 def time_for(value) if value.respond_to? :to_time value.to_time elsif value.is_a? Time value elsif value.respond_to? :new_offset # DateTime#to_time does the same on 1.9 d = value.new_offset 0 t = Time.utc d.year, d.mon, d.mday, d.hour, d.min, d.sec + d.sec_fraction t.getlocal elsif value.respond_to? :mday # Date#to_time does the same on 1.9 Time.local(value.year, value.mon, value.mday) elsif value.is_a? Numeric Time.at value else Time.parse value.to_s end rescue ArgumentError => boom raise boom rescue Exception raise ArgumentError, "unable to convert #{value.inspect} to a Time object" end |
- (Object) uri(addr = nil, absolute = true, add_script_name = true) Also known as: url, to
Generates the absolute URI for a given path in the app. Takes Rack routers and reverse proxies into account.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/aldebaran/base.rb', line 130 def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ uri = [host = ""] if absolute host << "http#{'s' if request.secure?}://" 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 |