Permalink
Browse files

make time_for part of the API

  • Loading branch information...
1 parent cc2f250 commit 9385dd878bc773fdd700cc79645425e801c06bdd @rkh rkh committed Aug 23, 2011
Showing with 36 additions and 7 deletions.
  1. +31 −0 README.rdoc
  2. +4 −6 lib/sinatra/base.rb
  3. +1 −1 test/helpers_test.rb
View
31 README.rdoc
@@ -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
10 lib/sinatra/base.rb
@@ -419,12 +419,8 @@ def not_found?
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 @@ def time_for(value)
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
2 test/helpers_test.rb
@@ -869,7 +869,7 @@ def obj.is_a?(thing) 60.is_a?(thing) end
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.

0 comments on commit 9385dd8

Please sign in to comment.