- Use simple_calendar gem to easily generate calendars in a Rails project.
- Understand how the calendar is generated and how to customise it.
Simple calendar is a Rails gem that generates a calendar for use in your views.
You can use simple calendar to generate monthly and weekly calendars.
Add this into your Gemfile and do a bundle install:
gem "simple_calendar", "~> 2.0"
Once the gem is installed you can start using it to generate calendars in your views.
The month_calendar method will work as it should:
<%= month_calendar do |date| %>
<%= date %>
<% end %>
For single day events:
$ rails g scaffold Meeting name start_time:datetime
For multi-day events you will need to also have a end_time
column in your db table:
$ rails g scaffold Meeting name start_time:datetime end_time:datetime
Note: start_time
and end_time
are keywords that simple_calendar looks out for to match an event to a dated cell.
To add events to the calendar, you will need to add the instance variable (eg. @meetings) to the above syntax:
<%= month_calendar events: @meetings do |date, meetings| %>
<%= date %>
<% meetings.each do |meeting| %>
<div>
<%= meeting.name %>
</div>
<% end %>
<% end %>
Breaking down what's happening here:
- Each time it goes through the loop, a cell is created and appended to the calendar (which is a table).
- In each instance of
meeting
, there needs to be a:start_time
attribute that is of data type DateTime. - Simple Calendar will automatically match that
:start_time
value with thedate
value, and append themeeting.name
into the correct cell.
Knowing this is knowing 90% of the functionality of simple calendar, which is to generate a simple calendar capable of showing 'events' in the correctly dated cells.
To customise the look (to add custom Bootstrap or Semantic UI classes, for example), generate the simple_calendar view via Terminal:
$ rails g simple_calendar:views
This is generate a folder in app/views, where you can edit the view.
To change the format of the date displayed in each cell, use Rails' built-in methods.
For example, you can use .to_formatted_s(:short)
to change the display from 2016-10-24 to 24 Oct:
<div id="requests">
<%= month_calendar events: @requests do |date, requests| %>
<%= date.to_formatted_s(:short) %>
<% end %>
</div>
It's also possible to directly tweak the style of the calendar:
.simple-calendar {
.day {}
.wday-0 {}
.wday-1 {}
.wday-2 {}
.wday-3 {}
.wday-4 {}
.wday-5 {}
.wday-6 {}
.today {}
.past {}
.future {}
.start-date {}
.prev-month {}
.next-month { }
.current-month {}
.has-events {}
}
See original GitHub repo: https://github.com/excid3/simple_calendar
To see simple_calendar in action: http://task-runner.herokuapp.com/