Class: Pumi::DataFile

Inherits:
Object
  • Object
show all
Defined in:
lib/pumi/data_file.rb

Constant Summary collapse

DEFAULT_DATA_DIRECTORY =
File.join(File.expand_path("..", File.dirname(__dir__)), "data")
TYPES =
%w[provinces districts communes villages].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ DataFile

Returns a new instance of DataFile.

Raises:

  • (ArgumentError)


11
12
13
14
# File 'lib/pumi/data_file.rb', line 11

def initialize(type)
  @type = type.to_s
  raise ArgumentError, "#{type} is not included in #{TYPES}" unless TYPES.include?(@type)
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



9
10
11
# File 'lib/pumi/data_file.rb', line 9

def type
  @type
end

Instance Method Details

#read(data_directory: DEFAULT_DATA_DIRECTORY) ⇒ Object



16
17
18
# File 'lib/pumi/data_file.rb', line 16

def read(data_directory: DEFAULT_DATA_DIRECTORY)
  YAML.load_file(data_file(data_directory)).fetch(type)
end

#write(data, data_directory: DEFAULT_DATA_DIRECTORY) ⇒ Object



20
21
22
23
24
# File 'lib/pumi/data_file.rb', line 20

def write(data, data_directory: DEFAULT_DATA_DIRECTORY)
  return if data.empty?

  File.write(data_file(data_directory), { type => data.sort.to_h }.to_yaml)
end