Time of day attributes for your Rails model
This ruby gem converts time of day to seconds since midnight and back. The seconds value is stored in the database and can be used for calculations and validations.
gem install time_of_day_attr
Define the time of day attributes:
class BusinessHour < ActiveRecord::Base time_of_day_attr :opening, :closing end
Converts time of day to seconds since midnight when a string was set:
business_hour = BusinessHour.new(opening: '9:00', closing: '17:00') business_hour.opening => 32400 business_hour.closing => 61200
To convert back to time of day:
TimeOfDayAttr.l(business_hour.opening) => '9:00' TimeOfDayAttr.l(business_hour.closing) => '17:00'
You could also omit minutes at full hour:
TimeOfDayAttr.l(business_hour.opening, omit_minutes_at_full_hour: true) => '9'
The standard formats for conversion are 'default' and 'hour'.
en: time_of_day: formats: default: '%k:%M' hour: '%k'
You can overwrite them or use custom formats:
en: time_of_day: formats: custom: '%H-%M'
Pass the formats you want for conversion:
class BusinessHour < ActiveRecord::Base time_of_day_attr :opening, formats: [:custom] end
business_hour = BusinessHour.new(opening: '09-00') business_hour.opening => 32400 TimeOfDayAttr.l(business_hour.opening, format: :custom) => '09-00'
time of day field
To get a text field with the converted value:
<%= form_for(business_hour) do |f| %> <%= f.time_of_day_field(:opening) %> <% end %>