Class: Emendate::DateSegmenter

Inherits:
Object
  • Object
show all
Includes:
DateUtils
Defined in:
lib/emendate/date_segmenter.rb

Constant Summary collapse

SEPTYPES =

Segment types to be treated as date separators after initial date segmentation and application of modifiers

%i[and or comma pipe]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DateUtils

#expand_shorter_digits, #is_range?, #max_season, #min_season, #month_abbr_literal, #month_literal, #possible_range?, #valid_date?, #valid_day?, #valid_month?, #valid_month_or_season?, #valid_season?, #valid_year?

Constructor Details

#initialize(tokens) ⇒ DateSegmenter

Returns a new instance of DateSegmenter.



18
19
20
21
22
23
# File 'lib/emendate/date_segmenter.rb', line 18

def initialize(tokens)
  @origtokens = tokens
  @working = tokens.class.new.copy(tokens)
  @result = tokens.class.new.copy(tokens)
  result.clear
end

Class Method Details

.callObject



9
10
11
# File 'lib/emendate/date_segmenter.rb', line 9

def call(...)
  new(...).call
end

Instance Method Details

#callObject



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
51
52
53
54
55
56
57
58
59
60
# File 'lib/emendate/date_segmenter.rb', line 25

def call
  recursive_parse until working.empty?

  %i[partial before after era_bce].each do |mod|
    working.copy(result)
    result.clear
    apply_modifiers(mod) until working.empty?
  end

  separators = result.select { |seg| SEPTYPES.include?(seg.type) }
  return Success(result) if separators.empty?

  if separators.map(&:type).uniq.length > 1
    return Failure(Emendate::SegmentSet.new(segments: [
      Emendate::DateTypes::Error.new(
        sources: result, error_type: :unprocessable,
        message: "Multiple date separator types"
      )
    ]))
  else
    transform_separators(separators)
  end
rescue Emendate::InvalidDateError => e
  Failure(Emendate::SegmentSet.new(segments: [
    Emendate::DateTypes::Error.new(
      sources: result, error_type: :invalid, exception: e
    )
  ]))
rescue Emendate::ForbiddenSegmentAdditionError => e
  result << Emendate::DateTypes::Error.new(
    sources: origtokens, error_type: :unprocessable, exception: e
  )
  Failure(result)
else
  Success(result)
end