File: utc_offset.rb

package info (click to toggle)
ruby-icalendar 2.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 492 kB
  • sloc: ruby: 2,868; makefile: 5
file content (50 lines) | stat: -rw-r--r-- 1,185 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require 'ostruct'

module Icalendar
  module Values
    class UtcOffset < Value
      def initialize(value, params = {})
        if value.is_a? Icalendar::Values::UtcOffset
          value = value.value
        else
          value = OpenStruct.new parse_fields(value)
        end
        super value, params
      end

      def behind?
        return false if zero_offset?
        value.behind
      end

      def value_ical
        "#{behind? ? '-' : '+'}#{'%02d' % hours}#{'%02d' % minutes}#{'%02d' % seconds if seconds > 0}"
      end

      def to_s
        str = "#{behind? ? '-' : '+'}#{'%02d' % hours}:#{'%02d' % minutes}"
        if seconds > 0
          "#{str}:#{'%02d' % seconds}"
        else
          str
        end
      end

      private

      def zero_offset?
        hours == 0 && minutes == 0 && seconds == 0
      end

      def parse_fields(value)
        md = /\A(?<behind>[+-])(?<hours>\d{2})(?<minutes>\d{2})(?<seconds>\d{2})?\z/.match value.gsub(/\s+/, '')
        {
          behind: (md[:behind] == '-'),
          hours: md[:hours].to_i,
          minutes: md[:minutes].to_i,
          seconds: md[:seconds].to_i
        }
      end
    end
  end
end