Sha256: 2a26a0f8164fccdda6604f8e068b28441ab4ec2d2e3455d00aade69ae144c1dc

Contents?: true

Size: 1.92 KB

Versions: 6

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

require_dependency "mr_common/application_record"

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

6 entries across 6 versions & 1 rubygems

Version Path
mr_common-1.1.0 app/models/mr_common/reminder.rb
mr_common-1.0.5 app/models/mr_common/reminder.rb
mr_common-1.0.4 app/models/mr_common/reminder.rb
mr_common-1.0.3 app/models/mr_common/reminder.rb
mr_common-1.0.2 app/models/mr_common/reminder.rb
mr_common-1.0.1 app/models/mr_common/reminder.rb