Class: Numeric

Inherits:
Object
  • Object
show all
Defined in:
lib/duration.rb

Overview

The following important additions are made to Numeric:

Numeric#weeks – Create a Duration object with given weeks Numeric#days – Create a Duration object with given days Numeric#hours – Create a Duration object with given hours Numeric#minutes – Create a Duration object with given minutes Numeric#seconds – Create a Duration object with given seconds

BigDuration support:

Numeric#years – Create a BigDuration object with given years Numeric#months – Create a BigDuration object with given months

BigDuration objects can be created from regular weeks, days, hours, etc by providing ‘:big’ as an argument to the above Numeric methods.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Intercept calls to .weeks, .days, .hours, .minutes and .seconds because Rails defines its own methods, so I’d like to prevent any redefining of Rails’ methods. If these methods don’t get captured, then alternatively Numeric#duration can be used.

BigDuration methods include .years and .months, also BigDuration objects can be created from any time such as weeks or minutes and even seconds.

*Example: BigDuration*

5.years => #<BigDuration: 5 years> 10.minutes(:big) => #<BigDuration: 10 minutes>

Example

140.seconds => #<Duration: 2 minutes and 20 seconds>



486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/duration.rb', line 486

def method_missing(method, *args)
	if [:weeks, :days, :hours, :minutes, :seconds].include? method
		if args.size > 0 && args[0] == :big
			duration(method, BigDuration)
		else
			duration(method)
		end
	elsif [:years, :months].include? method
		duration(method, BigDuration)
	else
		__numeric_old_method_missing(method, *args)
	end
end

Instance Method Details

#__numeric_old_method_missingObject



446
# File 'lib/duration.rb', line 446

alias __numeric_old_method_missing method_missing

#duration(part = nil, klass = Duration) ⇒ Object

Create a Duration object using self where self could represent weeks, days, hours, minutes, and seconds.

Example

10.duration(:weeks) => #<Duration: 10 weeks> 10.duration => #<Duration: 10 seconds>



458
459
460
461
462
463
464
# File 'lib/duration.rb', line 458

def duration(part = nil, klass = Duration)
	if [:years, :months, :weeks, :days, :hours, :minutes, :seconds].include? part
		klass.new(part => self)
	else
		klass.new(self)
	end
end