Permalink
Browse files

Allow default units to be specified

  • Loading branch information...
1 parent 5631d81 commit c523fed4b0feba768758316b8ba0255d534c2554 @ianlevesque ianlevesque committed Jun 4, 2011
Showing with 8 additions and 4 deletions.
  1. +4 −4 lib/chronic_duration.rb
  2. +4 −0 spec/chronic_duration_spec.rb
View
@@ -18,8 +18,8 @@ def self.raise_exceptions=(value)
# Given a string representation of elapsed time,
# return an integer (or float, if fractions of a
# second are input)
- def parse(string)
- result = calculate_from_words(cleanup(string))
+ def parse(string, opts = {})
+ result = calculate_from_words(cleanup(string), opts)
result == 0 ? nil : result
end
@@ -113,12 +113,12 @@ def humanize_time_unit(number, unit, pluralize, keep_zero)
res
end
- def calculate_from_words(string)
+ def calculate_from_words(string, opts)
val = 0
words = string.split(' ')
words.each_with_index do |v, k|
if v =~ float_matcher
- val += (convert_to_number(v) * duration_units_seconds_multiplier(words[k + 1] || 'seconds'))
+ val += (convert_to_number(v) * duration_units_seconds_multiplier(words[k + 1] || (opts[:default_unit] || 'seconds')))
end
end
val
@@ -43,6 +43,10 @@
ChronicDuration.parse('12 mins 3 seconds').is_a?(Integer).should be_true
end
+ it "should be able to parse minutes by default" do
+ ChronicDuration.parse('5', :default_unit => "minutes").should == 300
+ end
+
@exemplars.each do |k, v|
it "should properly parse a duration like #{k}" do
ChronicDuration.parse(k).should == v

0 comments on commit c523fed

Please sign in to comment.