Permalink
Browse files

flatten and flatten! methods for ActiveSupport::Duration

  • Loading branch information...
Ionatan Wiznia
Ionatan Wiznia committed Oct 11, 2013
1 parent 0061c5e commit 90871f7198f0739c82df2f1bbb66c5f8dd5a720a
@@ -1,3 +1,10 @@
+* Add `flatten` and `flatten!` methods to Duration objects.
+
+ Example:
+ Date.today + (1.month + 1.month).flatten == Date.today + 2.months
+
+ *Ionatan Wiznia*
+
* `require_dependency` accepts objects that respond to `to_path`, in
particular `Pathname` instances.
@@ -81,6 +81,18 @@ def as_json(options = nil) #:nodoc:
to_i
end
+ # Flattens all the +parts+ of the duration, and returns a
+ # new duration object.
+ def flatten
+ Duration.new(@value, flatten_parts)
+ end
+
+ # Flattens all the +parts+ of this duration.
+ def flatten!
+ @parts = flatten_parts
+ self
+ end
+
protected
def sum(sign, time = ::Time.current) #:nodoc:
@@ -97,6 +109,14 @@ def sum(sign, time = ::Time.current) #:nodoc:
end
end
+ def flatten_parts
+ @parts.inject({}) do |result, (name, value)|
+ result[name] ||= 0
+ result[name] += value
+ result
+ end.to_a
+ end
+
private
def method_missing(method, *args, &block) #:nodoc:
@@ -145,6 +145,21 @@ def test_to_json
assert_equal '172800', 2.days.to_json
end
+ def test_flatten
+ a = 2.months
+ b = (1.month + 1.month).flatten
+
+ assert_equal a.parts, b.parts
+ end
+
+ def test_flatten!
+ a = (1.month + 1.month)
+ b = a.flatten
+ a.flatten!
+
+ assert_equal a.parts, b.parts
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
@@ -3699,6 +3699,21 @@ Time.utc(1582, 10, 3) + 5.days
# => Mon Oct 18 00:00:00 UTC 1582
```
+When addinng or substracting durations, the resulting duration will be equivalent to subsequent calls to since or advance, so:
+
+```ruby
+Date.new(2013,1,28) + 1.month + 1.month
+# => Thu, 28 Mar 2013
+```
+
+If you want to add durations and then use them as just one call to since or advance, you can use the flatten or flatten! method:
+
+```ruby
+Date.new(2013,1,31) + (1.month + 1.month).flatten
+# => Sun, 31 Mar 2013
+```
+
+
Extensions to `File`
--------------------

0 comments on commit 90871f7

Please sign in to comment.