Relative time in a day, in a week, etc.
Pull request Compare This branch is 67 commits ahead of manveru:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.gitignore
.rspec
.rvmrc
Changelog.rdoc
Gemfile
Guardfile
MIT-LICENSE
README.rdoc
Rakefile
TODO
relativity.gemspec

README.rdoc

Relativity

Time, Date and DateTime classes don't have a mode for working with relative time inside 1 day (or 1 week, 1 month, 1 quarter, etc.).

A relative time object, relative to a day or a week, is useful to describe e.g. opening hours of a business. Time ranges are built on top, so the ranges of opening hours can be represented.

Not compatible with ruby 1.8.x

Example

require 'relativity'
opens_at = DayTime.new(9) #=> 09:00:00
closes_at = DayTime.new(12,30) #=> 12:30:00

opens_at = DayTime.new("8:35") #=> 08:35:00
closes_at = DayTime.new("17:59:30") #=> 17:59:30

dt = DayTime.new #=> 21:17:40
dt.seconds_since_midnight #=> #<BigDecimal:9d35d48,'0.7666056825 7238E5',18(45)>
dt.hours #=> 21
dt.minutes #=> 17
dt.seconds #=> 40
dt.nano_seconds #=> 568257238

dtr = DayTimeRange.new("8 to 12:30") # => 08:00:00 to 12:30:00
dtr.start # => 08:00:00
dtr.end # => 12:30:00
dtr.to_s # => "08:00:00 to 12:30:00"

night_shift = DayTimeRange.new("21:45..06:05") # => 21:45:00..06:05:00

wrong_format = DayTimeRange.new("11 to 15", :separator => '..')
Relativity::InvalidRangeFormatError: Maybe the range separator was not set correctly? Separator used was ".."

# normalize is intended for persisting a DayTime and DayTimeRange.

DayTime.normalize("8") # => "08:00:00"
DayTime.normalize(nil) # => nil
DayTimeRange.normalize("8..12") # => "08:00:00..12:00:00"
DayTimeRange.normalize("8 to 12", :separator => "..")
# => Relativity::InvalidRangeFormatError: Maybe the range separator\
     was not set correctly? Separator used was ".."
DayTimeRange.normalize(nil) # => nil

# persisting in ActiveRecord (>= 3.2.x)

class Shop < ActiveRecord::Base

  def opening_hours=(dtr)
    super(
      begin
        DayTimeRange.normalize(dtr, separator => '..')
      rescue Relativity::FormatError
        nil # or set a special error code here
      end)
    end
  end

  def opening_hours
    dtr = super and DayTimeRange.new(dtr, :separator => '..')
  end

end