Class: ProductTaxonomy::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/product_taxonomy/loader.rb

Class Method Summary collapse

Class Method Details

.load(data_path:) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/product_taxonomy/loader.rb', line 8

def load(data_path:)
  ProductTaxonomy.data_path = data_path

  return if ProductTaxonomy::Category.all.any?

  values_path = File.join(data_path, "values.yml")
  attributes_path = File.join(data_path, "attributes.yml")
  return_reasons_path = File.join(data_path, "return_reasons.yml")
  disclosures_path = File.join(data_path, "disclosures.yml")
  categories_glob = Dir.glob(File.join(data_path, "categories", "*.yml"))

  begin
    ProductTaxonomy::Value.load_from_source(YAML.load_file(values_path))
    ProductTaxonomy::Attribute.load_from_source(YAML.load_file(attributes_path))
    ProductTaxonomy::ReturnReason.load_from_source(YAML.load_file(return_reasons_path))
    ProductTaxonomy::Disclosure.load_from_source(YAML.load_file(disclosures_path))

    categories_source_data = categories_glob.each_with_object([]) do |file, array|
      array.concat(YAML.safe_load_file(file))
    end
    ProductTaxonomy::Category.load_from_source(categories_source_data)
  rescue Errno::ENOENT => e
    raise ArgumentError, "File not found: #{e.message}"
  rescue Psych::SyntaxError => e
    raise ArgumentError, "Invalid YAML: #{e.message}"
  end

  # Run validations that can only be run after the taxonomy has been loaded.
  ProductTaxonomy::Value.all.each { |model| model.validate!(:taxonomy_loaded) }
  ProductTaxonomy::Disclosure.all.each { |model| model.validate!(:taxonomy_loaded) }
end