Building a calendar in Ruby on Rails with simple calendar gem

Tram Ho

Simple Calendar is a library designed to help developers build calendars quickly and easily. This library can render calendar very flexibly as render calendar with day view, week view, month view, etc. Moreover, it can also be used to render events on that calendar.

Setting

Add to Gemfile:

=> bundle install

Add the file app/assets/stylesheets/application.css

Using

Month Calendar

You can generate the calendar display by month using the following method:

The default start_date params will be the current date.

Week Calendar

You can generate the calendar display by the week using the following method:

Where number_of_weeks is the number of weeks to display, the default will be 1.

Calendar with any number of days

Where number_of_days is the number of days to display, the default is 4.

Custom name params

The default params start_date will be used and displayed on the URL. To customize this params to another name, you may pass start_date_param in the calendar function as follows:

Rendering Events

The above methods you can use it to render calendars by month, week, day, … Here we will use it to render events on it.

  • Step 1:

Create model with 2 attributes needed: start_time and end_time . If that model only has the start_time attribute, it means it’s an event that only happens during the day. If there is both end_time, the event occurs within days.

I will create data for this event as follows:

  • Step 2

From the above model, I can query to get that event to display on the calendar as follows:

Next in the view, you just need to pass the events option. It will automatically render the date that the event occurs for each day on the calendar.

The result will look like this:

At this point, I have built a simple calendar according to my needs. Moreover, I can also customize that calendar’s View, please see its documentation Customizing The Calendar

References

https://github.com/excid3/simple_calendar

Share the news now

Source : Viblo