edtf 4.1.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ module EDTF
2
+
3
+ # The interface shared by all EDTF types:
4
+ # each one stands for a period of time.
5
+ module Period
6
+ include Comparable
7
+
8
+ PRECISIONS = %i[
9
+ century decade year season month day hour minute second
10
+ ].freeze
11
+
12
+ # Calendars by name, and the Ruby Date start of each
13
+ # (the day of the reform: Julian dates before it, Gregorian after).
14
+ # Any other reform day (a Julian day number) is a calendar, too.
15
+ CALENDARS = {
16
+ gregorian: ::Date::GREGORIAN,
17
+ julian: ::Date::JULIAN,
18
+ italy: ::Date::ITALY,
19
+ england: ::Date::ENGLAND
20
+ }.freeze
21
+
22
+ def earliest
23
+ self.begin
24
+ end
25
+
26
+ def latest
27
+ self.end
28
+ end
29
+
30
+ def to_range
31
+ self.begin..self.end
32
+ end
33
+
34
+ def to_s
35
+ edtf
36
+ end
37
+
38
+ def inspect
39
+ if respond_to?(:calendar) && self.calendar != :gregorian
40
+ calendar = " #{self.calendar}"
41
+ end
42
+ "#<#{self.class} #{edtf}#{calendar}>"
43
+ end
44
+
45
+ # The EDTF string, for JSON with or without ActiveSupport
46
+ # (whose Date#as_json would drop precision and qualifiers).
47
+ def as_json(*)
48
+ edtf
49
+ end
50
+
51
+ # Like Range#cover?: by the bounds only, not by precision.
52
+ # A time counts as its own calendar date in its own offset;
53
+ # nil bounds (open or unknown ends) reach without limit.
54
+ def cover?(other)
55
+ return false unless other.is_a?(Period) || Period.bounds(other)
56
+
57
+ first, last = Period.bounds(other)
58
+ (self.begin.nil? || (!first.nil? && self.begin <= first)) &&
59
+ (self.end.nil? || (!last.nil? && last <= self.end))
60
+ end
61
+
62
+ def ===(other)
63
+ cover?(other)
64
+ end
65
+
66
+ # Returns true if other is the same EDTF expression.
67
+ def eql?(other)
68
+ other.instance_of?(self.class) && state.eql?(other.state)
69
+ end
70
+
71
+ def hash
72
+ [self.class, *state].hash
73
+ end
74
+
75
+ # Ruby's Date#<=> coerces objects it doesn't know,
76
+ # so plain dates compare with periods without a core patch.
77
+ def coerce(other)
78
+ unless other.is_a?(::Date)
79
+ raise TypeError, "#{other.class} can't be coerced into #{self.class}"
80
+ end
81
+
82
+ [EDTF(other), self]
83
+ end
84
+
85
+ # Orders periods by begin, then end, then precision;
86
+ # qualifiers are ignored, so == means the same period.
87
+ def <=>(other)
88
+ other_keys = other.is_a?(Period) ? other.send(:keys) : Period.keys(other)
89
+ keys <=> other_keys if other_keys
90
+ end
91
+
92
+ def initialize_copy(other)
93
+ super
94
+ freeze
95
+ end
96
+
97
+ # Marshal restores objects without initialize; plain EDTF objects
98
+ # dump their instance variables and freeze on load.
99
+ # (EDTF::Date and EDTF::DateTime use Ruby's own hooks.)
100
+ def marshal_dump
101
+ instance_variables.to_h { |name| [name, instance_variable_get(name)] }
102
+ end
103
+
104
+ def marshal_load(variables)
105
+ variables.each { |name, value| instance_variable_set(name, value) }
106
+ freeze
107
+ end
108
+
109
+ def self.bounds(other) # :nodoc:
110
+ case other
111
+ when Period
112
+ [other.begin, other.end]
113
+ when ::DateTime, ::Time
114
+ [other.to_date] * 2
115
+ when ::Date
116
+ [::Date.jd(other.jd, ::Date::GREGORIAN)] * 2
117
+ end
118
+ end
119
+
120
+ # A calendar name (Symbol or String) or a Ruby Date start
121
+ # -> the calendar's name, or its reform day.
122
+ def self.calendar(value) # :nodoc:
123
+ case value
124
+ when nil
125
+ :gregorian
126
+ when Symbol, String
127
+ name = value.to_sym
128
+ return name if CALENDARS.key?(name)
129
+
130
+ raise ArgumentError, "unknown calendar: #{value}"
131
+ when Numeric
132
+ return CALENDARS.key(value) if CALENDARS.value?(value)
133
+ return value.to_i if value.finite? && value == value.to_i
134
+
135
+ raise ArgumentError, "invalid calendar: #{value}"
136
+ else
137
+ raise ArgumentError, "invalid calendar: #{value.inspect}"
138
+ end
139
+ end
140
+
141
+ # Years are stored as in ISO 8601 (astronomical numbering: 0 is 1 BC).
142
+ # Without year zero (historical numbering), years are written
143
+ # one lower before year 1: 1 BC is -1, 2 BC is -2.
144
+ def self.written_year(year, year_zero) # :nodoc:
145
+ year_zero || year.positive? ? year : year - 1
146
+ end
147
+
148
+ def self.astronomical_year(year, year_zero) # :nodoc:
149
+ year_zero || !year.negative? ? year : year + 1
150
+ end
151
+
152
+ # The Ruby Date start of a calendar.
153
+ def self.start(calendar) # :nodoc:
154
+ calendar = self.calendar(calendar)
155
+ CALENDARS.fetch(calendar, calendar)
156
+ end
157
+
158
+ def self.precision(other) # :nodoc:
159
+ case other
160
+ when Period
161
+ other.precision
162
+ when ::DateTime, ::Time
163
+ :second
164
+ else
165
+ :day
166
+ end
167
+ end
168
+
169
+ def self.keys(other) # :nodoc:
170
+ first, last = bounds(other)
171
+ [[0, first], [0, last], PRECISIONS.index(precision(other))] if first
172
+ end
173
+
174
+ private
175
+
176
+ def check_keys!(changes, allowed)
177
+ unknown = changes.keys - allowed
178
+ return if unknown.empty?
179
+
180
+ raise ArgumentError, "unknown keyword#{'s' if unknown.length > 1}: " \
181
+ "#{unknown.join(', ')}"
182
+ end
183
+
184
+ # Open bounds (nil) sort first at the start and last at the end.
185
+ # Private, but read from other periods too (see <=>).
186
+ def keys
187
+ [
188
+ self.begin ? [0, self.begin] : [-1],
189
+ self.end ? [0, self.end] : [1],
190
+ rank
191
+ ]
192
+ end
193
+
194
+ # Periods without a precision (intervals without dated ends) rank first.
195
+ def rank
196
+ PRECISIONS.index(precision) || -1
197
+ end
198
+ end
199
+ end
data/lib/edtf/season.rb CHANGED
@@ -1,199 +1,213 @@
1
1
  module EDTF
2
2
 
3
+ # EDTF covers seasons and other divisions of a year
4
+ # (ISO 8601-2 codes 21–41),
5
+ # and EDTF-Ruby provides a dedicated class for them:
6
+ #
7
+ # 21–24 spring, summer, autumn, winter (meteorological, northern)
8
+ # 25–28 the same, northern hemisphere
9
+ # 29–32 spring, summer, autumn, winter, southern hemisphere
10
+ # 33–36 quarters
11
+ # 37–39 quadrimesters (four months each)
12
+ # 40–41 semesters
13
+ #
14
+ # Note that EDTF does not make any assumption about the specifics
15
+ # (which months etc.) of the seasons;
16
+ # EDTF-Ruby uses meteorological seasons (three month periods),
17
+ # so winter (24, 28) and southern summer (30) reach into the next year.
18
+ #
19
+ # Qualifier and unspecified bitmasks cover the year and the code
20
+ # like a year and a month (2001-21?, 2001?-21, 200X-21).
3
21
  class Season
4
- extend Forwardable
5
-
6
- SEASONS = Hash[21, :spring, 22, :summer, 23, :autumn, 24, :winter].freeze
7
-
8
- CODES = Hash.new { |h,k| h.fetch(k.to_sym, nil) }.merge(
9
- SEASONS.invert).merge({ :fall => 23 }).freeze
10
-
11
- NORTHERN = Hash[:spring, [3,4,5], :summer, [6,7,8], :autumn, [9,10,11], :winter, [12,1,2]].freeze
12
- SOUTHERN = Hash[:autumn, [3,4,5], :winter, [6,7,8], :spring, [9,10,11], :summer, [12,1,2]].freeze
13
-
14
- NORTHERN_MONTHS = Hash[*NORTHERN.map { |s,ms| ms.map { |m| [m,s] } }.flatten].freeze
15
- SOUTHERN_MONTHS = Hash[*SOUTHERN.map { |s,ms| ms.map { |m| [m,s] } }.flatten].freeze
16
-
17
-
18
- include Comparable
19
- include Enumerable
20
-
21
- class << self
22
- def current
23
- Date.today.season
22
+ include Period
23
+
24
+ # The first month and the number of months of each division.
25
+ DIVISIONS = {
26
+ 21 => [3, 3], 22 => [6, 3], 23 => [9, 3], 24 => [12, 3],
27
+ 25 => [3, 3], 26 => [6, 3], 27 => [9, 3], 28 => [12, 3],
28
+ 29 => [9, 3], 30 => [12, 3], 31 => [3, 3], 32 => [6, 3],
29
+ 33 => [1, 3], 34 => [4, 3], 35 => [7, 3], 36 => [10, 3],
30
+ 37 => [1, 4], 38 => [5, 4], 39 => [9, 4],
31
+ 40 => [1, 6], 41 => [7, 6]
32
+ }.freeze
33
+
34
+ # The divisions that follow each other, in calendar order.
35
+ CYCLES = [
36
+ [21, 22, 23, 24], [25, 26, 27, 28], [31, 32, 29, 30],
37
+ [33, 34, 35, 36], [37, 38, 39], [40, 41]
38
+ ].freeze
39
+
40
+ MASK = Bitmask::YM
41
+
42
+ attr_reader :year, :season
43
+
44
+ def initialize(
45
+ year,
46
+ season,
47
+ uncertain: nil,
48
+ approximate: nil,
49
+ unspecified: nil,
50
+ calendar: nil,
51
+ year_zero: true
52
+ )
53
+ @year = Integer(year)
54
+ @season = Integer(season)
55
+ unless DIVISIONS.key?(@season)
56
+ raise ArgumentError, "invalid season: #{season}"
24
57
  end
25
- end
26
-
27
- attr_reader :season, :year
28
-
29
- attr_accessor :qualifier, :uncertain, :approximate
30
-
31
- def_delegators :to_range, *Range.instance_methods(false).reject { |m|
32
- m.to_s =~ /^(each|min|max|cover\?|inspect|to_s)$|^\W/
33
- }
34
58
 
35
- SEASONS.each_value do |s|
36
- define_method("#{s}?") { @season == s }
37
- define_method("#{s}!") { @season = s }
59
+ @uncertain = bits(uncertain)
60
+ @approximate = bits(approximate)
61
+ @unspecified = Bitmask.new(Bitmask.convert(unspecified) & Bitmask::YEAR)
62
+ @calendar = Period.calendar(calendar)
63
+ @historical = !year_zero
64
+ freeze
38
65
  end
39
66
 
40
- alias fall? autumn?
41
- alias fall! autumn!
67
+ attr_reader :uncertain, :approximate, :unspecified, :calendar
42
68
 
43
- [:first, :second, :third, :fourth].zip([:spring, :summer, :autumn, :winter]).each do |quarter, season|
44
- alias_method("#{quarter}?", "#{season}?")
45
- alias_method("#{quarter}!", "#{season}!")
69
+ # False if years are written without year 0 (1 BC is -0001).
70
+ def year_zero?
71
+ !@historical
46
72
  end
47
73
 
74
+ def precision
75
+ :season
76
+ end
48
77
 
49
- def initialize(*arguments)
50
- arguments.flatten!
51
- raise ArgumentError, "wrong number of arguments (#{arguments.length} for 0..3)" if arguments.length > 3
78
+ def values
79
+ [year, season]
80
+ end
52
81
 
53
- if arguments.length == 1
54
- case arguments[0]
55
- when Date
56
- @year, @season = arguments[0].year, NORTHERN_MONTHS[arguments[0]]
57
- when Symbol, String
58
- @year, @season = Date.today.year, SEASONS[CODES[arguments[0].to_sym]]
59
- else
60
- self.year = arguments[0]
61
- @season = NORTHERN_MONTHS[Date.today.month]
62
- end
63
- else
64
- self.year = arguments[0] || Date.today.year
65
- self.season = arguments[1] || NORTHERN_MONTHS[Date.today.month]
66
- self.qualifier = qualifier
67
- end
82
+ def uncertain?(part = nil)
83
+ qualified?(uncertain, part)
68
84
  end
69
85
 
86
+ def approximate?(part = nil)
87
+ qualified?(approximate, part)
88
+ end
70
89
 
71
- [:uncertain, :approximate].each do |m|
90
+ def unspecified?(part = nil)
91
+ qualified?(unspecified, part)
92
+ end
72
93
 
73
- define_method("#{m}?") { !!send(m) }
94
+ def with(**changes)
95
+ return self if changes.empty?
74
96
 
75
- define_method("#{m}!") do
76
- send("#{m}=", true)
77
- self
78
- end
79
- end
97
+ attributes = %i[year season uncertain approximate unspecified]
98
+ check_keys!(changes, attributes)
80
99
 
81
- def certain?; !uncertain; end
82
- def precise?; !approximate; end
100
+ values = attributes.to_h { |name|
101
+ [name, changes.fetch(name) { send(name) }]
102
+ }
83
103
 
84
- def certain!
85
- @uncertain = false
86
- self
104
+ self.class.new(
105
+ values.delete(:year),
106
+ values.delete(:season),
107
+ **values,
108
+ calendar: calendar,
109
+ year_zero: year_zero?
110
+ )
87
111
  end
88
112
 
89
- def precise!
90
- @approximate = false
113
+ def begin
114
+ first, = DIVISIONS[season]
115
+ ::Date.new(years.first, first, 1, Period.start(calendar))
91
116
  end
92
117
 
93
- # Returns the next season.
94
- def succ
95
- s = dup
96
- s.season = next_season_code
97
- s.year = year + 1 if s.first?
98
- s
118
+ def end
119
+ first, months = DIVISIONS[season]
120
+ date = ::Date.new(years.last, first, 1, Period.start(calendar))
121
+ date.next_month(months).prev_day
99
122
  end
100
123
 
101
- # def next(n = 1)
102
- # end
103
-
104
- def cover?(other)
105
- return false unless other.respond_to?(:day_precision)
106
- other = other.day_precision
107
- min.day_precision! <= other && other <= max.day_precision!
108
- end
124
+ # Returns the next season, or division of the same kind, in calendar order.
125
+ # Unspecified digits step by the unit they leave open.
126
+ def succ(by = 1)
127
+ cycle = CYCLES.find { |codes| codes.include?(season) }
128
+ shift, index = (cycle.index(season) + by).divmod(cycle.length)
109
129
 
110
- def each(&block)
111
- if block_given?
112
- to_range.each(&block)
113
- self
114
- else
115
- to_enum
130
+ year = self.year + shift
131
+ unless unspecified.zero? || shift.zero?
132
+ bound = shift.positive? ? years.last : years.first
133
+ year = Period.written_year(bound + shift, year_zero?)
134
+ sign = year.negative? ? -1 : 1
135
+ year = unspecified.min([year.abs])[0]
136
+ if year.zero? && (sign.negative? || !year_zero?)
137
+ year = unspecified.least_year(year)
138
+ end
139
+ year = Period.astronomical_year(sign * year, year_zero?)
116
140
  end
117
- end
118
141
 
119
- def year=(new_year)
120
- @year = new_year.to_i
142
+ with(year: year, season: cycle[index])
121
143
  end
122
144
 
123
- def season=(new_season)
124
- @season = SEASONS[new_season] || SEASONS[CODES[new_season]] ||
125
- raise(ArgumentError, "unknown season/format: #{new_season.inspect})")
126
- end
127
-
128
- def season?; true; end
129
-
130
- def qualified?; !!@qualifier; end
145
+ alias next succ
131
146
 
132
- def edtf
133
- '%04d-%2d%s%s%s' % [
134
- year,
135
- CODES[season],
136
- uncertain? ? '?' : '',
137
- approximate? ? '~' : '',
138
- qualified? ? "^#{qualifier}" : ''
139
- ]
147
+ def prev(by = 1)
148
+ succ(-by)
140
149
  end
141
150
 
142
- alias to_s edtf
151
+ def edtf
152
+ sign = written_year.negative? ? '-' : ''
153
+ values = [format('%04d', written_year.abs), season.to_s]
143
154
 
155
+ return sign + unspecified.masks(values).join('-') unless unspecified.zero?
144
156
 
145
- def <=>(other)
146
- case other
147
- when Date
148
- cover?(other) ? 0 : to_date <=> other
149
- when Interval
150
- (c = other <=> self) && -c
151
- when Epoch
152
- [min, max] <=> [other.min, other.max]
153
- when Season
154
- [year, month, qualifier] <=> [other.year, other.month, other.qualifier]
155
- else
156
- nil
157
+ values = uncertain.marks(values, '?') unless uncertain.zero?
158
+ unless approximate.zero?
159
+ values = approximate.marks(values, '~').map { |value|
160
+ value.sub(/~\?|\?~/, '%')
161
+ }
157
162
  end
158
- rescue
159
- nil
160
- end
161
163
 
162
- def ===(other)
163
- (self <=> other) == 0
164
- rescue
165
- false
164
+ sign + values.join('-')
166
165
  end
167
166
 
168
- def to_date
169
- Date.new(year, month, 1)
167
+ protected
168
+
169
+ def state
170
+ [
171
+ year,
172
+ season,
173
+ uncertain.value,
174
+ approximate.value,
175
+ unspecified.value,
176
+ calendar,
177
+ year_zero? || unspecified.zero?
178
+ ]
170
179
  end
171
180
 
172
- alias min to_date
181
+ private
173
182
 
174
- def max
175
- to_date.months_since(2).end_of_month
183
+ def bits(value)
184
+ mask = value == true ? MASK : Bitmask.convert(value)
185
+ Bitmask.new(mask & MASK)
176
186
  end
177
187
 
178
- # Returns a Range that covers the season (a three month period).
179
- def to_range
180
- min .. max
188
+ def qualified?(mask, part)
189
+ part.nil? ? !mask.zero? : mask.intersect?(part)
181
190
  end
182
191
 
183
- protected
184
-
185
- def month
186
- NORTHERN[@season][0]
192
+ def written_year
193
+ Period.written_year(year, year_zero?)
187
194
  end
188
195
 
189
- def season_code
190
- CODES[season]
191
- end
196
+ # The first and last year the unspecified digits allow,
197
+ # from the written year.
198
+ def years
199
+ return year..year if unspecified.zero?
192
200
 
193
- def next_season_code(by = 1)
194
- ((season_code + by) % 4) + 20
195
- end
201
+ low, = unspecified.min([written_year.abs])
202
+ high, = unspecified.max([written_year.abs])
203
+ if low.zero? && (written_year.negative? || !year_zero?)
204
+ low = unspecified.least_year(low)
205
+ end
196
206
 
207
+ years = written_year.negative? ? [-high, -low] : [low, high]
208
+ first, last = years.map { |y| Period.astronomical_year(y, year_zero?) }
209
+ first..last
210
+ end
197
211
  end
198
212
 
199
213
  end