2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rails simple_calendar実装メモ

Last updated at Posted at 2024-08-15

■ インストール
GemFileに以下記述

#calender ui
gem "simple_calendar", "~> 2.0"

bundleで installをする

bundle install 

■ 実装してみる(scssで)
ファイル作成
app\assets\stylesheets\custom_calendar.scss

@import "simple_calendar";
.simple-calendar{
    thead {
・・・その他記述可能

■ erbファイル実装
.erbファイル にscss読み込み

  <%= stylesheet_link_tag "custom_calendar", media: "print, screen", "data-turbo-track": "reload" %>

実装こういう感じ

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

■ イベントなど設定
controller

  def calendar
    start_date = params.fetch(:start_date, Date.today).to_date
    @event_days = EventDay.where(start_time: start_date.beginning_of_month.beginning_of_week..start_date.end_of_month.end_of_week)
  end 

表示

  <%= month_calendar(events: @event_days) do |date, event_days| %>
        <div class="day_block">
            <div>
            &nbsp;
            </div>
            <div class="day_num">
              <%= date.day %>
            </div>
            <div class="day_text  ">
            <% if event_days.length > 0 %>
             <%= event_days[0].name %>
            <% elsif date.wday == 3 %>
              休業日
            <% else %>
            &nbsp;
            <% end %>
            </div>
        </div>
    <% end %>

■ カスタムで実装する
テンプレート生成

rails g simple_calendar:views

ファイル作成される

create  app/views/simple_calendar
create  app/views/simple_calendar/_calendar.html.erb
create  app/views/simple_calendar/_month_calendar.html.erb
create  app/views/simple_calendar/_week_calendar.html.erb

■祝日などを独自に定義
app/helpers/holiday_helper.rb

module HolidayHelper
  def holiday_class(day, current_month)
      "holiday" #modelなどをよんで条件による実装など
  end
 end

app/views/simple_calendar/_month_calendar.html.erb
元ソースに holiday_class として追加した。 start_date.monthは選択されている月

            <%= content_tag :td, class: [calendar.td_classes_for(day), holiday_class(day, start_date.month)].compact.join(' ') do %>

元ソース

            <%#= content_tag :td, class: calendar.td_classes_for(day) do %>
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?