From 9385dd878bc773fdd700cc79645425e801c06bdd Mon Sep 17 00:00:00 2001 From: Konstantin Haase Date: Tue, 23 Aug 2011 15:29:38 +0200 Subject: [PATCH] make time_for part of the API --- README.rdoc | 31 +++++++++++++++++++++++++++++++ lib/sinatra/base.rb | 10 ++++------ test/helpers_test.rb | 2 +- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/README.rdoc b/README.rdoc index 77e48812..715832a9 100644 --- a/README.rdoc +++ b/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 find_template helper is used to find template files for rendering: diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index ad599d87..208fd514 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -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. diff --git a/test/helpers_test.rb b/test/helpers_test.rb index 85464776..eeb6e339 100644 --- a/test/helpers_test.rb +++ b/test/helpers_test.rb @@ -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.