Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to store and display a day of the week?

I'm relatively new to Ruby. I need to keep track of a day of the week on my activity model. The code that I have so far doesn't seem like the most elegant solution. I am wondering if there is a better way.

So far, this is what I have in my form:

<%= form_for(@activity) do |f| %>
  <div class="field">
    <%= f.label :day %><br />
    <%= f.select :day, [['Sunday', 0], ['Monday', 1], ['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5], ['Saturday', 6]] %>
  </div>
<% end %>

And when I need to display the day of the week:

<% days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] %>
<% @activities.each do |activity| %>
  <%= days[activity.day.to_i] %>
<% end %>

How can I do this better? Feel free to mention any library/gem that I may not be aware of.

Solution:

Ruby provides the Date::DAYNAMES constant which is an array of days of the week. We can reuse that in our code:

<%= form_for(@activity) do |f| %>
  <div class="field">
    <%= f.label :day %><br />
    <%= f.select :day, Date::DAYNAMES.zip((0..6).to_a) %>
  </div>
<% end %>

<% @activities.each do |activity| %>
  <%= Date::DAYNAMES[activity.day.to_i] %>
<% end %>
like image 362
Andrew Avatar asked Jul 06 '11 00:07

Andrew


1 Answers

In the latest versions you can define an enum with that constant and then use it for different things:

In migration, day_of_week is integer

In model:

enum :day_of_week => Date::DAYS_INTO_WEEK

And then you can use searches in model

Model.day_of_weeks.keys[0..4] will return ['monday', 'tuesday', .... 'friday']

Model.monday is equivalent to Model.where("day_of_week = ?", 'monday')

http://api.rubyonrails.org/classes/ActiveRecord/Enum.html

like image 85
Sergio Ocón-Cárdenas Avatar answered Sep 23 '22 11:09

Sergio Ocón-Cárdenas