diff --git a/README.md b/README.md index 7e6e0c3..9fae795 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,20 @@ Haml & HTML: ``` +### helper `time_tag_interval` + +The same with `time_tag` but made for time intervals + +```haml += time_tag_interval Time.parse("14 March 1879"), Time.parse("18 April 1955"), :format => '%d %h %Y' += time_tag_interval Time.parse("14 March 1989"), 150.hours, :format => :short +``` + +```html + + +``` + ### ActiveRecord::Base#html\_schema\_type ```ruby diff --git a/lib/green_monkey/ext/view_helper.rb b/lib/green_monkey/ext/view_helper.rb index 78abf12..7c69b3f 100644 --- a/lib/green_monkey/ext/view_helper.rb +++ b/lib/green_monkey/ext/view_helper.rb @@ -10,21 +10,51 @@ module ViewHelper # = time_tag post.created_at # = time_tag post.created_at, format: "%d %h %Y %R%p" # = time_tag post.created_at, itemprop: "datePublished" - def time_tag(date_or_time, *args) + def time_tag(time, *args) options = args.extract_options! format = options.delete(:format) || :long + datetime = time_to_iso8601(time) - if date_or_time.acts_like?(:time) + + if time.acts_like?(:time) title = nil - content = args.first || I18n.l(date_or_time, format: format) - datetime = date_or_time.iso8601(10) - elsif date_or_time.kind_of?(Numeric) - title = ChronicDuration.output(date_or_time, :format => format) - content = distance_of_time_in_words(date_or_time) - datetime = ChronicDuration.output(date_or_time, :format => :iso8601) + content = args.first || I18n.l(time, format: format) + elsif time.kind_of?(Numeric) + title = ChronicDuration.output(time, :format => format) + content = args.first || distance_of_time_in_words(time) end content_tag(:time, content, options.reverse_merge(datetime: datetime, title: title)) end + + def time_tag_interval(from, to, *args) + options = args.extract_options! + format = options.delete(:format) || :long + + datetime = [from, to].map(&method(:time_to_iso8601)).join("/") + content = args.first || [from, to].map do |time| + if time.acts_like?(:time) + I18n.l(from, format: format) + else + ChronicDuration.output(time, :format => format) + end + end + + if to.acts_like?(:time) + content = content.join(" - ") + else + content = content.join(" in ") + end + + content_tag(:time, content, options.reverse_merge(datetime: datetime)) + end + + def time_to_iso8601(time) + if time.acts_like?(:time) + time.iso8601 + elsif time.kind_of?(Numeric) + ChronicDuration.output(time, :format => :iso8601) + end + end end end \ No newline at end of file diff --git a/spec/haml_spec.rb b/spec/haml_spec.rb index a80aa46..4ad4ace 100644 --- a/spec/haml_spec.rb +++ b/spec/haml_spec.rb @@ -34,22 +34,6 @@ def render_haml(template, options = {}) render_haml("%b[:title] Dada").should =~ /itemprop=.?title/ end - it "should run time_tag with time" do - time = Time.now - str = render_haml("= time_tag(time)", time: time) - - str.should =~ / '%d %h %Y')", time: time) + str.should =~ / :short)", time: time) + str.should =~ /