Module: SmartEnum::YamlStore

Included in:
SmartEnum
Defined in:
lib/smart_enum/yaml_store.rb

Defined Under Namespace

Classes: AmbiguousSource

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.data_rootObject



38
39
40
# File 'lib/smart_enum/yaml_store.rb', line 38

def self.data_root
  @data_root
end

.data_root=(val) ⇒ Object



42
43
44
# File 'lib/smart_enum/yaml_store.rb', line 42

def self.data_root=(val)
  @data_root = val
end

Instance Method Details

#register_values_from_file!Object

Loads values from a YAML file or files

Looks for a file or directory named after the enum type in the data root. If a directory is found, values from all of the YAML files in that directory are loaded. Otherwise, values are loaded from the file named after the enum.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/smart_enum/yaml_store.rb', line 13

def register_values_from_file!
  unless SmartEnum::YamlStore.data_root
    raise "Must set SmartEnum::YamlStore.data_root before using `register_values_from_file!`"
  end
  unless self.name
    raise "Cannot infer data file for anonymous class"
  end

  basename = SmartEnum::Utilities.tableize(self.name)
  dirname = File.join(SmartEnum::YamlStore.data_root, basename)
  inferred_file = File.join(SmartEnum::YamlStore.data_root, "#{basename}.yml")
  files = if Dir.exists?(dirname)
            if File.exists?(inferred_file)
              raise AmbiguousSource, "#{self} values should be defined in inferred file or directory, not both"
            end
            Dir[File.join(dirname, "*.yml")]
          else
            [inferred_file]
          end
  files.each do |file_path|
    values = YAML.load_file(file_path)
    register_values(values, self, detect_sti_types: true)
  end
end