2019-10-05 20:37:23 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module ActiveSupport
|
|
|
|
# Reads a YAML configuration file, evaluating any ERB, then
|
|
|
|
# parsing the resulting YAML.
|
|
|
|
#
|
|
|
|
# Warns in case of YAML confusing characters, like invisible
|
|
|
|
# non-breaking spaces.
|
|
|
|
class ConfigurationFile # :nodoc:
|
|
|
|
class FormatError < StandardError; end
|
|
|
|
|
|
|
|
def initialize(content_path)
|
2020-02-10 18:12:33 -05:00
|
|
|
@content_path = content_path.to_s
|
2019-10-05 20:37:23 -04:00
|
|
|
@content = read content_path
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.parse(content_path, **options)
|
|
|
|
new(content_path).parse(**options)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse(context: nil, **options)
|
2020-02-10 13:14:46 -05:00
|
|
|
YAML.load(render(context), **options) || {}
|
2019-10-05 20:37:23 -04:00
|
|
|
rescue Psych::SyntaxError => error
|
|
|
|
raise "YAML syntax error occurred while parsing #{@content_path}. " \
|
|
|
|
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
|
|
|
|
"Error: #{error.message}"
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def read(content_path)
|
|
|
|
require "yaml"
|
|
|
|
require "erb"
|
|
|
|
|
|
|
|
File.read(content_path).tap do |content|
|
2020-02-15 15:37:01 -05:00
|
|
|
if content.include?("\u00A0")
|
2020-12-23 05:07:37 -05:00
|
|
|
warn "#{content_path} contains invisible non-breaking spaces, you may want to remove those"
|
2019-10-05 20:37:23 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2020-02-10 13:14:46 -05:00
|
|
|
|
|
|
|
def render(context)
|
2020-02-10 17:14:48 -05:00
|
|
|
erb = ERB.new(@content).tap { |e| e.filename = @content_path }
|
2020-02-10 13:14:46 -05:00
|
|
|
context ? erb.result(context) : erb.result
|
|
|
|
end
|
2019-10-05 20:37:23 -04:00
|
|
|
end
|
|
|
|
end
|