• Stars
    star
    1,476
  • Rank 31,835 (Top 0.7 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A wonderfully simple calendar gem for Rails

Simple Calendar

πŸ“† A calendar for your Ruby on Rails app.

Build Status Gem Version

Simple Calendar is designed to do one thing really really well: render a calendar.

It lets you render a calendar of any size. Maybe you want a day view, a 4 day agenda, a week view, a month view, or a 6 week calendar. You can do all of that with the new gem, just give it a range of dates to render.

It doesn't depend on any ORM so you're free to use it with ActiveRecord, Mongoid, any other ORM, or pure Ruby objects.

Thanks to all contributors for your wonderful help!

calendar

Installation

Just add this into your Gemfile followed by a bundle install:

gem "simple_calendar"

If you're using Bootstrap, the calendar should already have a border and nice spacing for days.

Optionally, you can include the default stylesheet for the calendar in your app/assets/stylesheets/application.css file:

*= require simple_calendar

or in your SCSS app/assets/stylesheets/application.scss file:

@import "simple_calendar";

Usage

Generating calendars is extremely simple with simple_calendar.

The first parameter is a symbol that looks up the current date in params. If no date is found, it will use the current date.

In these examples, we're using :start_date which is the default.

Month Calendar

You can generate a calendar for the month with the month_calendar method.

<%= month_calendar do |date| %>
  <%= date %>
<% end %>

To show the day of the month instead of the date, use <%= date.day %>

Week Calendar

You can generate a week calendar with the week_calendar method.

<%= week_calendar(number_of_weeks: 2) do |date| %>
  <%= date %>
<% end %>

Setting number_of_weeks is optional and defaults to 1.

Custom Length Calendar

You can generate calendars of any length by passing in the number of days you want to render.

<%= calendar(number_of_days: 4) do |date| %>
  <%= date %>
<% end %>

Setting number_of_days is optional and defaults to 4.

Custom Parameter Name

You can pass in start_date_param to change the name of the parameter in the URL for the current calendar view.

<%= calendar(start_date_param: :my_date) do |date| %>
  <%= date %>
<% end %>

Custom Partial

You can set a different partial name for calendars by passing the partial path.

<%= calendar(partial: 'products/calendar') do |date| %>
  <%= date %>
<% end %>

Internationalization (I18n)

The default views are prepared to do translation lookups for month names and weekdays.

To profit from that, you can take advantage of the rails-i18n gem which comes with translations for many languages already.

In a Rails 6 app, the configuration could look like the following:

  • Add gem 'rails-i18n' to your Gemfile and run bundle.
  • Define the available and default locale e.g. in config/application.rb:
# config/application.rb
config.i18n.available_locales = [:en, :de, :fr]
config.i18n.default_locale = :en
  • Define the following translation keys:
# e.g. config/locales/de.yml
de:
  simple_calendar:
    previous: "<<"
    next: ">>"
    week: Woche

See the Rails I18n Guide for further information.

Rendering Events

What's a calendar without events in it? There are two simple steps for creating calendars with events.

The first step is to add the following to your model. We'll be using a model called Meeting, but you can add this to any model or Ruby object.

Here's an example model:

# single day events
$ rails g scaffold Meeting name start_time:datetime

# multi-day events
$ rails g scaffold Meeting name start_time:datetime end_time:datetime

By default it uses start_time as the attribute name. If you'd like to use another attribute other than start_time, just pass it in as the attribute

<%= month_calendar(attribute: :starts_at) do |date| %>
  <%= date %>
<% end %>

Optionally the end_time attribute can be used which enables multi-day event rendering.

Just pass in the attribute and end_attribute options respectively

<%= month_calendar(attribute: :start_date, end_attribute: :end_date) do |date| %>
  <%= date %>
<% end %>

If you already have a model with a start time attribute called something other than start_time or accesses it through a relationship, you can alias the attribute by defining a start_time method in the my_model.rb file and not have to specify it separately as in the above example

class MyModel
    ## Other code related to your model lives here

    def start_time
        self.my_related_model.start ##Where 'start' is a attribute of type 'Date' accessible through MyModel's relationship
    end
end

In your controller, query for these meetings and store them in an instance variable. Normally you'll want to search for the ones that only show up inside the calendar view (for example, you may only want to grab the events for the current month).

We'll just load up all the meetings for this example.

def index
  # Scope your query to the dates being shown:
  start_date = params.fetch(:start_date, Date.today).to_date
  @meetings = Meeting.where(starts_at: start_date.beginning_of_month.beginning_of_week..start_date.end_of_month.end_of_week)
end

Then in your view, you can pass in the events option to render. The meetings will automatically be filtered out by day for you.

<%= month_calendar(events: @meetings) do |date, meetings| %>
  <%= date %>

  <% meetings.each do |meeting| %>
    <div>
      <%= meeting.name %>
    </div>
  <% end %>
<% end %>

If you pass in objects that don't respond to the attribute method (like starts_at), then all the meetings will be yielded each day. This lets you do custom filtering however you want.

Customizing The Calendar

There are a handful of configuration options that you can use in simple_calendar.

Customizing Views

You can customize the layouts for each of the calendars by running the generators for simple_calendar:

$ rails g simple_calendar:views

This will generate a folder in app/views called simple_calendar that you edit to your heart's desire.

Time Zones

Setting Time.zone will make sure the calendar start days are correctly computed in the right timezone. You can set this globally in your application.rb file or if you have a User model with a time_zone attribute, you can set it on every request by using a before_action like the following example.

This code example uses Devise's current_user and user_signed_in? methods to retrieve the user's timezone and set it for the duration of the request. Make sure to change the :user_signed_in? and current_user methods if you are using some other method of authentication.

class ApplicationController < ActionController::Base
  before_action :set_time_zone, if: :user_signed_in?

  private

    def set_time_zone
      Time.zone = current_user.time_zone
    end
end

If you want to set the time zone globally, you can set the following in config/application.rb:

config.time_zone = 'Central Time (US & Canada)'

Beginning Of Week

You can also change the beginning day of the week by setting Date.beginning_of_week in a before_action just like in the previous example. If you want to set this globally, you can put this line in config/application.rb:

config.beginning_of_week = :sunday

Custom CSS Classes

Setting classes on the table and elements are pretty easy.

simple_calendar comes with a handful of useful classes for each day in the calendar that you can use:

.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 {}
}

Just paste this into a CSS file and add your styles and they will be applied to the calendar. All of these classes are inside of the simple-calendar class so you can scope your own classes with similar names.

Custom Header Title And Links

Header and title links are easily adjusted by generating views and modifying them inside your application.

For example, if you'd like to use abbreviated month names, you can modify the views from this:

<%= t('date.month_names')[start_date.month] %> <%= start_date.year %>

To

<%= t('date.abbr_month_names')[start_date.month] %> <%= start_date.year %>

Your calendar will now display "Sep 2015" instead of "September 2015" at the top! :)

AJAX Calendars

Rendering calendars that update with AJAX is pretty simple. You'll need to follow these steps.

  • Run rails g simple_calendar:views to generate the views.
  • Add an ID to the calendar view's outer div. <div id="calendar" class="simple-calendar">
  • Add remote: true option to the next & preview links like this.
  • Create js.erb file to respond to JS requests, render the new calendar, and replace the calendar on the page by ID like this.

The response can simply replace the HTML of the div with the newly rendered calendar.

Take a look at excid3/simple_calendar-ajax-example to see how it is done.

If you are using Hotwire, just wrap in a Turbo Frame. Like this:

<%= turbo_frame_tag 'calendar' do %>
  <%= month_calendar do |date| %>
    <%= date.day %>
  <% end %>
<% end %>

Custom Calendars

The three main calendars available should take care of most of your needs, but simple_calendar makes it easy to create completely custom calendars (like maybe you only want business weeks).

If you'd like to make a completely custom calendar, you can create a new class that inherits from SimpleCalendar::Calendar. The name you give it will correspond to the name of the template it will try to render.

The main method you'll need to implement is the date_range so that your calendar can have a custom length.

class SimpleCalendar::BusinessWeekCalendar < SimpleCalendar::Calendar
  private

    def date_range
      beginning = start_date.beginning_of_week + 1.day
      ending    = start_date.end_of_week - 1.day
      (beginning..ending).to_a
    end
end

To render this in the view, you can do:

<%= render SimpleCalendar::BusinessWeekCalendar.new(self, events: meetings) do |date| %>
  <%= date %>
<% end %>

And this will render the app/views/simple_calendar/_business_week_calendar.html.erb partial.

You can copy one of the existing templates to use for the partial for your new calendar.

View Specs and Tests

If you're running view specs against views with calendars, you may run into route generation errors like the following:

Failure/Error: render
ActionView::Template::Error:
  No route matches {:action=>"show", :controller=>"controller_name", :start_date=>Sun, 29 Mar 2015}

If so, you can stub out the appropriate method like so (rspec 3 and up):

expect_any_instance_of(SimpleCalendar::Calendar).to receive(:link_to).at_least(:once).and_return("")

With modifications as appropriate.

Author

Chris Oliver [email protected]

https://gorails.com

@excid3

License

Simple Calendar is licensed under the MIT License.

More Repositories

1

noticed

Notifications for Ruby on Rails applications
Ruby
2,415
star
2

jumpstart

Easily jumpstart a new Rails application with a bunch of great features by default
HTML
1,200
star
3

tailwindcss-stimulus-components

A set of StimulusJS components for TailwindCSS apps similar to Bootstrap JS components.
JavaScript
1,083
star
4

madmin

A robust Admin Interface for Ruby on Rails apps
JavaScript
514
star
5

receipts

Easy receipts and invoices for your Rails applications
Ruby
495
star
6

simple_discussion

A simple, extensible Rails forum
Ruby
368
star
7

prefixed_ids

Friendly Prefixed IDs for your Ruby on Rails models
Ruby
198
star
8

revise_auth

A pure Rails authentication system like Devise.
Ruby
192
star
9

stack_rescue

A gem for Rails to automatically search Google for exceptions raised in your Rails applications
Ruby
171
star
10

esbuild-rails

Esbuild Rails plugin
JavaScript
137
star
11

signalman

Development tools for Ruby on Rails
Ruby
92
star
12

beginnerbounties.com

Small Projects for Junior Developers
Ruby
77
star
13

dotfiles

My personal dotfiles for macOS: zsh, MacVim, iterm, and more.
Vim Script
70
star
14

stimulus-slimselect

A Stimulus wrapper around SlimSelect
JavaScript
66
star
15

python-apt

This is a Python library interface to libapt, which allows you to query and manipulat APT package repository information using the Python programming language.
C++
63
star
16

combined_time_select

A Rails time_select like Google Calendar with combined hour and minute time_select
Ruby
60
star
17

logbot

A minimal IRC bot for logging channels
Python
59
star
18

textual-solarized

A port of the Solarized theme to Textual IRC
JavaScript
31
star
19

simple_calendar-ajax-example

An example Rails application to demonstrate SimpleCalendar AJAX next/previous links
Ruby
29
star
20

scheduled_tweets

Ruby
28
star
21

gorails-forum

Ruby
24
star
22

betterminitest.com

Learn how to write better Minitest tests
CSS
21
star
23

Rails-Learning

List of resources to learning this amazing platform for building top-quality web apps with Ruby on Rails! ❀
20
star
24

railshackathon.com

The RailsHackathon.com website
HTML
19
star
25

ferrum_pdf

A PDF generator for Rails using Ferrum & headless Chrome
Ruby
19
star
26

trello-stimulus-reflex

A trello clone using Stimulus Reflex
Ruby
17
star
27

asdf-vars

An asdf extension that safely sets global and per-project environment variables, based upon rbenv
Shell
17
star
28

railsconf-2020-actiontext

Railsconf 2020 example app for showcasing ActionText
Ruby
16
star
29

nine_to_five

Ruby
14
star
30

oauthable

Setup, test, and implement the OAuth connections to over 70 different APIs.
Ruby
13
star
31

gorails-ruby

An interactive CLI for GoRails, Railsbytes, Jumpstart, and more.
Ruby
12
star
32

animatedgif.me-v2

Ruby
11
star
33

keryx

Python
11
star
34

current_projects

Lists a user's active github projects
Ruby
9
star
35

israilsdead.com

It's pretty self explanatory I think
HTML
9
star
36

urlgrabber

A high-level cross-protocol url-grabber
Python
8
star
37

Sublime-Ruby-on-Rails.tmLanguage

8
star
38

fluttrly

An elegantly simple todo list
Ruby
8
star
39

zapier

Zapier API Rubygem
Ruby
8
star
40

excid3-wordpress-theme

My wordpress theme for excid3.com
PHP
7
star
41

simpyl_pastebin

A simple python pastebin
Python
7
star
42

animatedgifme

A ruby library for http://animatedgif.me
Ruby
7
star
43

weather_underground

A Ruby gem for the Weather Underground API
Ruby
7
star
44

wistia-player-speed

Add 2x, 1.5x, 0.5x speeds and skip 30 seconds controls to your Wistia video player
HTML
7
star
45

mail_drop

Record and view Rails ActionMailer emails sent in development
Ruby
7
star
46

stimulus-js-2.0

A look at Stimulus JS 2.0's new Values and CSS Classes APIs
Ruby
6
star
47

railsconf-2021

Realtime Rails applications with Hotwire & ActionMailbox
Ruby
6
star
48

superleggera

Monitor your CSS in development to create a whitelist for PurgeCSS in Rails with Webpacker
Ruby
6
star
49

deploy_test

See how to deploy Rails to Ubuntu with Capistrano
Ruby
5
star
50

feedforward.io

Curating articles that inspire discussion
Ruby
5
star
51

clickable-simple_calendar

An example how to make the dates clickable with simple_calendar for creating new events
Ruby
5
star
52

particlesjs-rails-example

Ruby
5
star
53

webhookmonitor.com

A tool for recording and monitoring webhooks
Ruby
4
star
54

rpi-pms5003

Raspberry Pi air quality monitoring with PMS5003 and Ruby
Ruby
4
star
55

chef-rails-stack

Chef Solo recipes to setup a Rails stack on Ubuntu 12.04 LTS
Ruby
4
star
56

cfps

Conference talk submissions (CFPs)
4
star
57

landing

My new website landing page
CSS
4
star
58

vuejs-rails-markdown-field

Use VueJS to add markdown previews to any Rails form input field or text area.
Ruby
4
star
59

react-todolist

A react todo list application with Ruby on Rails
Ruby
4
star
60

better_resources

Resources routes that use the same for new and edit so users get less 404s
Ruby
3
star
61

rails-5.2-actiontext

Testing ActionText in Rails 5.2
Ruby
3
star
62

irc_bothost

A Django web application for maintaining python IRC bots
Python
3
star
63

simple_calendar-example

A simple calendar gem example with Rails 6
Ruby
3
star
64

sponsor-hub

A hub for your GitHub sponsors
Ruby
3
star
65

excid3

3
star
66

simple_calendar-full-day-example

Ruby
3
star
67

download_counter

A download counter implemented in Rails3 with an administration interface
Ruby
3
star
68

administrate-trix-editor

Episode 211: Adding the Trix Editor as an Administrate Custom Field
Ruby
3
star
69

excid3.com

Moving to Jekyll
HTML
3
star
70

gemspec-cheatsheet

An interactive GemSpec cheat sheet
3
star
71

reply_parser

Parser for email replies
Ruby
3
star
72

animatedgif.me

With Great Gifs Comes Great Responsibility
Ruby
3
star
73

turbolinks-3-example

Ruby
3
star
74

imageme

Ruby
2
star
75

unwrapt

A pure python layer for offline package managers
Python
2
star
76

chromium

cluster rendering
C
2
star
77

googleweather

Ruby client for the undocumented Google Weather API
Ruby
2
star
78

lithoslabs.com

2
star
79

keryx_profiler

A website to maintain user submitted profiles for Keryx
Ruby
2
star
80

cultivate

Ruby
2
star
81

blogspam

A Ruby and/or Rails client for Blogspam.net
Ruby
2
star
82

pastebot

An IRC bot that accepts pastes, uploads them, and notifies recipients
Python
2
star
83

excid3bot

A hubot
CoffeeScript
2
star
84

cdnjs-rails

A mechanized way to pull in one to many CDNJS libraries with fall back to local installed versions.
Ruby
2
star
85

panopticode

Social Volt Contest Entry
Ruby
2
star
86

hatchbox-marketing

2
star
87

rugby

A Ruby IRC bot
Ruby
2
star
88

trackler

A package tracker visualizing progress on Google Maps
Ruby
2
star
89

No-Net-Debs

List and download deb packages for updates (dist-upgrade included) or new package(s) for a computer without Internet. Hosting in case http://ubuntu.no.sapo.pt/nonetdebs/nonetdebs goes down.
2
star
90

fluttr-desktop

Fluttr desktop application in Python and GTK
Python
2
star
91

omniauth-stripeplatform

A strategy for omniauth and the new beta Stripe.com platofrm.
Ruby
1
star
92

simple_map

Ruby
1
star
93

hacker_rank

A Ruby interface to the HackerRank / InterviewStreet API
Ruby
1
star
94

anonykron

anonykron.com
Ruby
1
star
95

confab

A NodeJS IRC client in the browser
JavaScript
1
star
96

taip-parser

Ruby
1
star
97

ipcommerce

Ruby
1
star
98

omniauth-linode

An Omniauth Strategy for Linode's v4 API
Ruby
1
star
99

ice_rocket

A Rubygem for the IceRocket API
Ruby
1
star
100

combined_time_select-example

Ruby
1
star