A ruby gem to master time of day attributes in Rails
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
config/locales
lib
test
.gitignore
Gemfile
Gemfile.lock
README.md
Rakefile
time_of_day_attr.gemspec

README.md

Time of day attributes for your Rails model

Gem Version Code Climate License

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.

Installation

gem install time_of_day_attr

Usage

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'

Formats

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 %>

License

MIT