Sha256: 69fcd3683bee28ae9628f1fccf71345733412fe8154db363758fa79306355f1d

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module MrCommon
  class Reminder < ApplicationRecord
    class << self
      def time_zone_options
        ActiveSupport::TimeZone::MAPPING.values.sort
      end
    end

    validates :start_time, presence: true
    validates :end_time, presence: true
    validates :location, presence: true
    validates :summary, presence: true
    validates :slug, presence: true, uniqueness: true
    validates :start_time, presence: true
    validates :all_day, inclusion: [true, false]
    validates :time_zone, presence: true, inclusion: Reminder.time_zone_options, if: -> { time_zone.present? }

    before_validation :parameterize_slug

    def to_ical
      cal = Icalendar::Calendar.new

      cal.add_timezone(TZInfo::Timezone.get(time_zone).ical_timezone(start_time))
      cal.event do |e|
        e.dtstart = calendar_start_time
        e.dtend = calendar_end_time
        e.summary = summary
        e.location = location
        e.description = description
      end
      cal.publish
      cal.to_ical
    end

    private

      def parameterize_slug
        self.slug = slug.parameterize.gsub(/(\W|_)/, "-")
      end

      def calendar_time_zone
        time_zone || "Etc/UTC"
      end

      def calendar_start_time
        if all_day?
          Icalendar::Values::DateOrDateTime.new(start_date_string, tzid: calendar_time_zone).call
        else
          Icalendar::Values::DateOrDateTime.new(start_time, tzid: calendar_time_zone)
        end
      end

      def calendar_end_time
        if all_day?
          Icalendar::Values::DateOrDateTime.new(end_date_string, tzid: calendar_time_zone).call
        else
          Icalendar::Values::DateOrDateTime.new(end_time, tzid: calendar_time_zone)
        end
      end

      def start_date_string
        start_time.strftime("%Y%m%d")
      end

      def end_date_string
        end_time.strftime("%Y%m%d")
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mr_common-1.0.0 app/models/mr_common/reminder.rb