Class: Apia::FieldSpec::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/apia/field_spec.rb

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ Parser

Returns a new instance of Parser.



54
55
56
57
58
59
60
61
# File 'lib/apia/field_spec.rb', line 54

def initialize(string)
  @string = string
  @paths = Set.new
  @excludes = Set.new
  @type = :normal
  @last_word = ''
  @sections = []
end

Instance Method Details

#parseObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/apia/field_spec.rb', line 63

def parse
  @string.each_char do |character|
    case character
    when ','
      next if @last_word.empty?

      add_last_word

    when '['
      if @last_word.empty?
        raise FieldSpecParseError, '[ requires a word before it'
      end

      @sections << @last_word
      @paths << @sections.join('.')
      @last_word = ''

    when ']'
      if @sections.last.nil?
        raise FieldSpecParseError, 'unopened bracket closure'
      end

      add_last_word unless @last_word.empty?

      @sections.pop

    when /\s+/
      # Ignore whitespace

    when '-'
      if @last_word.empty?
        @type = :exclude
      else
        add_last_word
      end

    when 'a'..'z', '0'..'9', '_', '*'
      @last_word += character

    else
      raise FieldSpecParseError, "invalid character #{character}"
    end
  end

  unless @sections.empty?
    raise FieldSpecParseError, 'unbalanced brackets'
  end

  add_last_word

  FieldSpec.new(@paths, excludes: @excludes, parsed_string: @string)
end