Skip to content

Commit

Permalink
Add namespaces to YAML sources per rubyconfig#288
Browse files Browse the repository at this point in the history
  • Loading branch information
wwboynton committed Mar 6, 2021
1 parent 618c839 commit 567d4f1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/config/sources/yaml_source.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ module Sources
class YAMLSource
attr_accessor :path

def initialize(path)
def initialize(path, namespace = nil)
@path = path.to_s

# Make sure @namespace is an array if it exists at all
if namespace
@namespace = namespace
@namespace = [@namespace] unless @namespace.is_a?(Array)
end
end

# returns a config hash from the YML file
def load
result = YAML.load(ERB.new(IO.read(@path)).result) if @path and File.exist?(@path)

result || {}
return {} unless result
return result unless @namespace

# Resolves namespacing multiple layers deep
# i.e. ['layer1', 'layer2'] comes out to {'layer1' => {'layer2' => content}}
return result = @namespace.reverse.inject(result) { |a, n| { n => a } }


rescue Psych::SyntaxError => e
raise "YAML syntax error occurred while parsing #{@path}. " \
Expand Down
37 changes: 37 additions & 0 deletions spec/sources/yaml_source_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,43 @@ module Config::Sources
end
end

context "basic yml file with single namespace" do
let(:source) do
YAMLSource.new "#{fixture_path}/development.yml", 'test_namespace'
end

it "should properly read the settings" do
results = source.load
expect(results['test_namespace']["size"]).to eq(2)
end

it "should properly read nested settings" do
results = source.load
pp results
expect(results['test_namespace']["section"]["size"]).to eq(3)
expect(results['test_namespace']["section"]["servers"]).to be_instance_of(Array)
expect(results['test_namespace']["section"]["servers"].size).to eq(2)
end
end

context "basic yml file with nested namespace" do
let(:source) do
YAMLSource.new "#{fixture_path}/development.yml", ['test_namespace', 'test_layer_2']
end

it "should properly read the settings" do
results = source.load
expect(results['test_namespace']['test_layer_2']["size"]).to eq(2)
end

it "should properly read nested settings" do
results = source.load
expect(results['test_namespace']['test_layer_2']["section"]["size"]).to eq(3)
expect(results['test_namespace']['test_layer_2']["section"]["servers"]).to be_instance_of(Array)
expect(results['test_namespace']['test_layer_2']["section"]["servers"].size).to eq(2)
end
end

context "yml file with erb tags" do
let(:source) do
YAMLSource.new "#{fixture_path}/with_erb.yml"
Expand Down

0 comments on commit 567d4f1

Please sign in to comment.