Yesterday night Ruby/Informix 0.7.0 escaped from my hands, after a vacational sprint that allowed Ruby/Informix to get new and important capabilities. The most obvious one is the support for the INTERVAL data type.
Actually, Ruby/Informix was able to handle insertion of INTERVAL data types already, because Informix accepts an ANSI SQL standard formatted string as an INTERVAL. Today, we can still use a String or use an Interval object for storing and also for retrieving INTERVAL data.
To create an Interval object you can write the following:
Interval = Informix::Interval
ym = Interval.year_to_month(2, 5)
ds = Interval.day_to_second(1, 2,
3, 4)
ym is an INTERVAL YEAR TO MONTH, while ds is an INTERVAL DAY TO FRACTION.
You don't need to specify all the fields of an INTERVAL.
Interval.year_to_month(2)
Interval.day_to_second(5)
Interval.year_to_month(:months => 3)
Interval.day_to_second(:hours => 2,
:minutes => 5)
You can even use fractions of years, days, hours, minutes or seconds:
Interval.year_to_month(1.5)
Interval.day_to_second(:hours => 1.5,
:minutes => 5)
You can use Rationals instead of Floats for exactitud:
Interval.year_to_month(0.3)
Interval.year_to_month(Rational(1,3))
This is specially important when working with small fractions of seconds:
Interval.day_to_second(:days=>123456789,
:seconds=>1.2)
Interval.day_to_second(:days=>123456789,
:seconds=>Rational(12,10))
Because when using Floats, there's a limit in the significant digits that can be stored that doesn't exist when using a Rational.
Interval objects have the ability to work with Date, DateTime and Time Ruby objects:
ym = Interval.year_to_month(1, 5)
today = Date.today
ym + today
ds = Interval.day_to_second(:hours=>3,
:minutes=> 10)
now = Time.now
ds + now
You can't mix INTERVAL YEAR TO MONTH with Time, or INTERVAL DAY TO FRACTION with Date, because are incompatible. If you still want to do something like that, you can use DateTime:
now = DateTime.now
ym = Interval.year_to_month(1, 5)
ds = Interval.day_to_second(:hours=>3,
:minutes=> 10)
ym + now
ds + now
But there's still more. What about if I want to know how many minutes are in 3 days and 4 hours?
ds = Interval.day_to_second(:days=> 3,
:hours=> 4)
ds.to_minutes
What about seconds
There are some things left to learn about Intervals, but this post has become too long. Don't forget to check the
documentation, which has been enriched with more examples.