make time_for part of the API

This commit is contained in:
Konstantin Haase 2011-08-23 15:29:38 +02:00
parent cc2f250205
commit 9385dd878b
3 changed files with 36 additions and 7 deletions

View File

@ -1119,6 +1119,37 @@ You can also pass it a file name:
"store it!"
end
=== Dealing with Date and Time
Sinatra offers a +time_for+ helper method, which, from the given value
generates a Time object. It is also able to convert +DateTime+, +Date+ and
similar classes.
get '/' do
pass if Time.now > time_for('Dec 23, 2012')
"still time"
end
This method is used internally by +expires+, +last_modified+ and akin. You can
therefore easily extend the behavior of those methods by overriding +time_for+
in your application.
helpers do
def time_for(value)
case value
when :yesterday then Time.now - 24*60*60
when :tomorrow then Time.now + 24*60*60
else super
end
end
end
get '/' do
last_modified :yesterday
expires :tomorrow
"hello"
end
=== Looking Up Template Files
The <tt>find_template</tt> helper is used to find template files for rendering:

View File

@ -419,12 +419,8 @@ module Sinatra
status == 404
end
private
# Ruby 1.8 has no #to_time method.
# This can be removed and calls to it replaced with to_time,
# if 1.8 support is dropped.
# Generates a Time object from the given value.
# Used by #expires and #last_modified.
def time_for(value)
if value.respond_to? :to_time
value.to_time
@ -450,6 +446,8 @@ module Sinatra
end
end
private
# Template rendering methods. Each method takes the name of a template
# to render as a Symbol and returns a String with the rendered output,
# as well as an optional hash with additional options.

View File

@ -869,7 +869,7 @@ class HelpersTest < Test::Unit::TestCase
end
end
wrapper = Object.new.extend Sinatra::Helpers
@last_modified_time = wrapper.send :time_for, last_modified_time
@last_modified_time = wrapper.time_for last_modified_time
end
# fixes strange missing test error when running complete test suite.