[Awesome Ruby Gem] Use working_hours gem to calculate working hours
working_hours
A modern ruby gem allowing to do time calculation with working hours.
Installation
You can install it as a gem:
1 | gem install working_hours |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Then, run bundle install
.
1 | bundle install |
Usages
1 | require 'working_hours' |
Configuration
The working hours configuration is thread safe and consists of a hash defining working periods for each day, a time zone and a list of days off. You can set it once, for example in a initializer for rails:
1 | # Configure working hours |
Or you can set it for the duration of a block with the with_config method, this is particularly useful with around_filter:
1 | WorkingHours::Config.with_config(working_hours: {mon:{'09:00' => '18:00'}}, holidays: [], time_zone: 'Paris') do |
with_config
uses keyword arguments, you can pass all or some of the supported arguments :
1 | working_hours |
Holiday hours
Sometimes you need to configure different working hours as a one-off, e.g. the working day might end earlier on Christmas Eve.
You can configure this with the holiday_hours option, either as an override on the existing working hours, or as a set of hours that are being worked on a holiday day.
If any hours are set for a calendar day in holiday_hours, then the working_hours for that day will be ignored, and only the entries in holiday_hours taken into consideration.
1 | # Configure holiday hours |
No core extensions / monkey patching
Core extensions (monkey patching to add methods on Time, Date, Numbers, etc.) are handy but not appreciated by everyone. WorkingHours can also be used without any monkey patching:
1 | require 'working_hours/module' |
Use in your class/module
If you want to use working hours only inside a specific class or module, you can include its computation methods like this:
1 | require 'working_hours/module' |
Timezones
This gem uses a simple but efficient approach in dealing with timezones. When you define your working hours you have to choose a timezone associated with it (in the config example, the working hours are in Paris time). Then, any time used in calculation will be converted to this timezone first, so you don’t have to worry if your times are local or UTC as long as they are correct :)
Alternatives
There is a gem called business_time - https://github.com/bokmann/business_time already available to do this kind of computation and it was of great help to us. But we decided to start another one because business_time is suffering from a few bugs and inconsistencies. It also lacks essential features to us (like working minutes computation).
Another gem called biz - https://github.com/zendesk/biz was released after working_hours to bring some alternative.
References
[2] working_hours | RubyGems.org | your community gem host - https://rubygems.org/gems/working_hours
[4] zendesk/biz: Time calculations using business hours. - https://github.com/zendesk/biz