Skip to content

Commit

Permalink
Merge pull request sinatra#199 from stjhimy/config_erb
Browse files Browse the repository at this point in the history
Allow erb syntax on yml config file
  • Loading branch information
Zachary Scott committed Jul 20, 2016
2 parents 642f8ee + de1dc88 commit 5a4cba9
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
10 changes: 8 additions & 2 deletions sinatra-contrib/lib/sinatra/config_file.rb
Expand Up @@ -128,9 +128,9 @@ def config_file(*paths)
Dir.chdir(root || '.') do
paths.each do |pattern|
Dir.glob(pattern) do |file|
raise UnsupportedConfigType unless ['.yml', '.erb'].include?(File.extname(file))
$stderr.puts "loading config file '#{file}'" if logging?
document = IO.read(file)
document = ERB.new(document).result if file.split('.').include?('erb')
document = ERB.new(IO.read(file)).result
yaml = config_for_env(YAML.load(document)) || {}
yaml.each_pair do |key, value|
for_env = config_for_env(value)
Expand All @@ -141,6 +141,12 @@ def config_file(*paths)
end
end

class UnsupportedConfigType < Exception
def message
'Invalid config file type, use .yml or .yml.erb'
end
end

private

# Given a +hash+ with some application configuration it returns the
Expand Down
Empty file.
1 change: 1 addition & 0 deletions sinatra-contrib/spec/config_file/key_value.yml
@@ -1,5 +1,6 @@
---
foo: bar
bar: <%= "bar" %>
something: 42
nested:
a: 1
Expand Down
16 changes: 15 additions & 1 deletion sinatra-contrib/spec/config_file_spec.rb
Expand Up @@ -22,7 +22,17 @@ def config_file(*args, &block)
expect(settings.nested[:a]).to eq(1)
end

it 'should render options in ERB tags' do
it 'should render options in ERB tags when using .yml files' do
config_file 'key_value.yml'
settings.bar.should == "bar"
settings.something.should == 42
settings.nested['a'].should == 1
settings.nested[:a].should == 1
settings.nested['b'].should == 2
settings.nested[:b].should == 2
end

it 'should render options in ERB tags when using .yml.erb files' do
config_file 'key_value.yml.erb'
expect(settings.foo).to eq("bar")
expect(settings.something).to eq(42)
Expand All @@ -32,6 +42,10 @@ def config_file(*args, &block)
expect(settings.nested[:b]).to eq(2)
end

it 'should raise error if config file extension is not .yml or .erb' do
expect{ config_file 'config.txt' }.to raise_error(Sinatra::ConfigFile::UnsupportedConfigType)
end

it 'should recognize env specific settings per file' do
config_file 'with_envs.yml'
expect(settings.foo).to eq('test')
Expand Down

0 comments on commit 5a4cba9

Please sign in to comment.