diff --git a/README.rdoc b/README.rdoc index 92d6719..32347a4 100644 --- a/README.rdoc +++ b/README.rdoc @@ -112,6 +112,7 @@ Forme ships with a bunch of built-in transformers that you can use: === +serializer+ :default :: returns HTML strings +:html_usa :: returns HTML strings, formats dates and times in American format without timezones :text :: returns plain text strings === +formatter+ diff --git a/lib/forme.rb b/lib/forme.rb index 58b6e70..34bf238 100644 --- a/lib/forme.rb +++ b/lib/forme.rb @@ -935,9 +935,9 @@ def call(tag) when Array tag.map{|x| call(x)}.join when DateTime, Time - tag.strftime("%F %H:%M:%S%Z") + format_time(tag) when Date - tag.strftime("%F") + format_date(tag) when Raw tag.to_s else @@ -957,6 +957,16 @@ def serialize_close(tag) private + # Return a string in ISO format representing the +Date+ instance. + def format_date(date) + date.strftime("%F") + end + + # Return a string in ISO format representing the +Time+ or +DateTime+ instance. + def format_time(time) + time.strftime("%F %H:%M:%S%Z") + end + # Escape ampersands, brackets and quotes to their HTML/XML entities. def h(string) string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] } @@ -970,6 +980,23 @@ def attr_html(tag) end end + # Overrides formatting of dates and times to use an American format without + # timezones. + module Serializer::AmericanTime + Forme.register_transformer(:serializer, :html_usa, Serializer.new.extend(self)) + + private + + # Return a string in American format representing the +Date+ instance. + def format_date(date) + date.strftime("%m/%d/%Y") + end + + # Return a string in American format representing the +Time+ or +DateTime+ instance, without the timezone. + def format_time(time) + time.strftime("%m/%d/%Y %I:%M:%S%p") + end + end # Serializer class that converts tags to plain text strings. # diff --git a/spec/forme_spec.rb b/spec/forme_spec.rb index 6f41519..821fd40 100644 --- a/spec/forme_spec.rb +++ b/spec/forme_spec.rb @@ -305,6 +305,12 @@ Forme::Form.new(:inputs_wrapper=>:table, :wrapper=>:trtd).inputs([:textarea]).to_s.should == '
' end + specify "serializer: html_usa formats dates and datetimes in American format without timezones" do + Forme::Form.new(:serializer=>:html_usa).tag(:div, :foo=>Date.new(2011, 6, 5)).to_s.should == '
' + Forme::Form.new(:serializer=>:html_usa).tag(:div, :foo=>DateTime.new(2011, 6, 5, 16, 3, 2)).to_s.should == '
' + Forme::Form.new(:serializer=>:html_usa).tag(:div, :foo=>Time.utc(2011, 6, 5, 4, 3, 2)).to_s.should == '
' + end + specify "serializer: text uses plain text output instead of html" do Forme::Form.new(:serializer=>:text).input(:textarea, :label=>"Foo", :value=>"Bar").to_s.should == "Foo: Bar\n\n" Forme::Form.new(:serializer=>:text).input(:text, :label=>"Foo", :value=>"Bar").to_s.should == "Foo: Bar\n\n"