0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails3.2でiCalendarを使う

Last updated at Posted at 2019-12-13

booked Schedularで予定をOutlookに取り込んだら便利だったので、Railsでもやりたくなった。

配布元

ググっても日本語で記事を書いている人が少ない。なぜ?

インストール

windowsでやってます。

> ruby -v
ruby 1.9.3
> gem install icalendar -v "2.4.1"

> bundle install

苦労したところ

先に苦労した書いておきたい。

ical形式とは?

まずHTMLじゃない。ical形式ってところから学ぶことになる。
カレンダーに使われるiCalendar形式について part1

ブラウザでアクセス

そしてHTMLじゃない。ブラウザでアクセスしてもicsファイルをダウンロードする。ダウンロードしたものが正しい記述なのか簡単に判断できない。

Outlookに取り込むまえ

予定表を開く > インターネットから
URLを入力してもへっぽこコードだと開かない。Railsのエラーもよくわからん。

ドはまりした認証

hoge/export_eventsってな名前で作成していたが、auth(認証ページ)で引っかかっていた。(気が付くのに時間が掛かった・・・)

before_filter :auth, :except=>[:export_events]

例外にしておく必要がある。(特定の人にだけ公開ってなことになると、どうすれば良いのかわからない)

コード

サンプルが少なくてお試しコードを作るのも一苦労した。

お試しコード

まずはOutlookに表示させることだけを考える。いろんな人の英知を参考にしたコードです。

  def export_events()
    require 'icalendar'
    cal = Icalendar::Calendar.new
    
    cal.append_custom_property("X-WR-CALNAME;VALUE=TEXT", "俺のカレンダー")
    cal.timezone do |t|
      t.tzid = 'Asia/Tokyo'
      t.standard do |s|
        s.tzoffsetfrom = '+0900'
        s.tzoffsetto   = '+0900'
        s.tzname       = 'JST'
        s.dtstart      = '19700101T000000'
      end
    end

    cal.event do |e|
      e.dtstart     = Icalendar::Values::DateTime.new('20191228T133000')
      e.dtend       = Icalendar::Values::DateTime.new('20191228T153000')
      e.summary     = "Meeting with the man."
      e.description = "Have a long lunch meeting and decide nothing..."
    end

    cal.publish
    headers['Content-Type'] = "text/calendar; charset=UTF-8"    
    render :text => cal.to_ical
  end

dtstartとdtendは近い日時にしておかないと表示を探さないといけない。地味にめんどい。
Outlookに取り込めたらこっちのモンです。

改造コード

cal.event do |e| このあたりを改造する。

日時形式を合わせる必要がある。改行コードは「\n」だった。

# params[:piyo]とかも使えたので、いくらでもやりようがある。
# hoge/export_events?piyo=fugafuga とか
    reservations = Hoge.all #実際には本日から1ヵ月ぐらいの範囲にした
      
    reservations.each do |res|
      cal.event do |e|
        e.dtstart = Icalendar::Values::DateTime.new(res.responding).strftime("%Y%m%dT%H%M%S")
        e.dtend = Icalendar::Values::DateTime.new(res.responding + 1.hour).strftime("%Y%m%dT%H%M%S")
        e.summary = res.member_name
        e.description = res.content + "\n\n" + res.memo
      end
    end

こんな感じで予定を作ります。

参考

Sinatra + icalendar Gemで予定をWebで配信するサンプル
RubyでiCalの作成とGoogleCalendarでの公開

追記

outlookに設定してからサーバのログを眺めると30分毎にアクセスがあります。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?