Class: Baan::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/baan/parser.rb

Defined Under Namespace

Classes: Result

Constant Summary collapse

DEFAULT_DATA_FILE =
Pathname(File.join(__dir__, "..", "data", "provinces.yml")).freeze
DEFAULT_ROOT_KEY =
"provinces".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Parser

Returns a new instance of Parser.



11
12
13
14
# File 'lib/baan/parser.rb', line 11

def initialize(**options)
  @data_file = options.fetch(:data_file) { DEFAULT_DATA_FILE }
  @root_key = options.fetch(:root_key) { DEFAULT_ROOT_KEY }
end

Instance Attribute Details

#data_fileObject (readonly)

Returns the value of attribute data_file.



9
10
11
# File 'lib/baan/parser.rb', line 9

def data_file
  @data_file
end

#root_keyObject (readonly)

Returns the value of attribute root_key.



9
10
11
# File 'lib/baan/parser.rb', line 9

def root_key
  @root_key
end

Instance Method Details

#parseObject



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

def parse
  data = YAML.load_file(data_file).fetch(root_key)
  districts = []
  villages = []
  provinces = data.map do |province_data|
    province = Province.new(
      parent_division: nil,
      subdivisions: [],
      latitude: nil,
      longitude: nil,
      **province_data.transform_keys(&:to_sym).except(:districts)
    )

    province_data.fetch("districts").map do |district_data|
      district = District.new(
        parent_division: province,
        subdivisions: [],
        latitude: nil,
        longitude: nil,
        **district_data.transform_keys(&:to_sym).except(:villages)
      )

      district_data.fetch("villages", []).map do |village_data|
        village = Village.new(
          parent_division: district,
          subdivisions: [],
          latitude: nil,
          longitude: nil,
          **village_data.transform_keys(&:to_sym)
        )
        district.subdivisions << village
        villages << village
        village
      end

      province.subdivisions << district
      districts << district
      district
    end

    province
  end

  Result.new(provinces:, districts:, villages:)
end