Module: Cumulus::Common::BaseLoader

Overview

Public: A module that handles loading all the 4 configuration files and creating objects from them.

Class Method Summary collapse

Class Method Details

.load_file(file, dir) ⇒ Object

Internal: Load a file. Will check if a file exists by the name passed in, or with a .json extension.

file - the name of the file to load dir - the directory the file is located in

Returns the contents of the file



71
72
73
74
75
76
77
78
79
80
# File 'lib/common/BaseLoader.rb', line 71

def self.load_file(file, dir)
  path = File.join(dir, file)
  if File.exist?(path)
    File.read(path)
  elsif File.exist?("#{path}.json")
    File.read("#{path}.json")
  else
    throw "File does not exist: #{path}"
  end
end

.resource(file, dir, json = true, &loader) ⇒ Object

Internal: Load the resource, passing the parsed JSON to the function passed in

file - the name of the file to load dir - the directory the file is located in json - indicates if the resources are in json format loader - the function that will handle the read json



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/common/BaseLoader.rb', line 29

def self.resource(file, dir, json = true, &loader)
  name = file.chomp(".json")

  begin
    contents = load_file(file, dir)
    loader.call(
      name,
      if json then JSON.parse(contents) else contents end
    )
  rescue => e
    puts "Unable to load resource #{file}: #{e}"
    puts e.backtrace
    nil
  end
end

.resources(dir, json = true, &individual_loader) ⇒ Object

Internal: Load the resources in a directory, handling each file with the function passed in.

dir - the directory to load resources from json - indicates if the resources are in json format individual_loader - the function that loads a resource from each file name

Returns an array of resources



16
17
18
19
20
# File 'lib/common/BaseLoader.rb', line 16

def self.resources(dir, json = true, &individual_loader)
  Dir.entries(dir)
  .reject { |f| f == "." or f == ".." or File.directory?(File.join(dir, f)) or f.end_with?(".swp") or f.end_with?("~") }
  .map { |f| resource(f, dir, json, &individual_loader) }.reject(&:nil?)
end

.template(file, dir, vars, &loader) ⇒ Object

Internal: Load the template, apply variables, and pass the parsed JSON to the function passed in

file - the name of the file to load dir - the directory the file is located in vars - the variables to apply to the template (can be nil) loader - the function that will handle the read json



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/common/BaseLoader.rb', line 52

def self.template(file, dir, vars, &loader)
  template = load_file(file, dir)
  if vars
    vars.each do |key, value|
      template.gsub!("{{#{key}}}", "#{value}")
    end
  end
  json = JSON.parse(template)

  loader.call(nil, json)
end