From ae52cf8df06effc8d06103b7ea970be1741f7baf Mon Sep 17 00:00:00 2001 From: "Shota Fukumori (sora_h)" Date: Thu, 2 Apr 2015 11:36:43 +0900 Subject: [PATCH] Expand variables correctly Previously this fails: Variable.call("${FOO} \\${FOO} ${FOO}", "FOO" => "BAR") #=> "BAR BAR ${FOO}" --- lib/dotenv/substitutions/variable.rb | 27 +++++++++------------------ spec/dotenv/parser_spec.rb | 1 + 2 files changed, 10 insertions(+), 18 deletions(-) diff --git a/lib/dotenv/substitutions/variable.rb b/lib/dotenv/substitutions/variable.rb index a4a7b7bd..c4688dd6 100644 --- a/lib/dotenv/substitutions/variable.rb +++ b/lib/dotenv/substitutions/variable.rb @@ -8,30 +8,21 @@ module Substitutions module Variable class << self VARIABLE = / - (\\)? # is it escaped with a backslash? - (\$) # literal $ - ( # collect braces with var for sub - \{? # allow brace wrapping - ([A-Z0-9_]+) # match the variable - \}? # closing brace - ) + (\\)? # is it escaped with a backslash? + (\$) # literal $ + \{? # allow brace wrapping + ([A-Z0-9_]+) # match the variable + \}? # closing brace /xi def call(value, env) - # Process embedded variables - value.scan(VARIABLE).each do |parts| - if parts.first == '\\' - # Variable is escaped, don't replace it. - replace = parts[1...-1].join("") + value.gsub(VARIABLE) do |value| + if $1 == '\\' + value[1..-1] else - # Replace it with the value from the environment - replace = env.fetch(parts.last) { ENV[parts.last] } + env.fetch($3) { ENV[$3] } end - - value = value.sub(parts[0...-1].join(""), replace || "") end - - value end end end diff --git a/spec/dotenv/parser_spec.rb b/spec/dotenv/parser_spec.rb index fab62757..e6d2277c 100644 --- a/spec/dotenv/parser_spec.rb +++ b/spec/dotenv/parser_spec.rb @@ -60,6 +60,7 @@ def env(string) it "does not expand escaped variables" do expect(env('FOO="foo\$BAR"')).to eql("FOO" => "foo$BAR") expect(env('FOO="foo\${BAR}"')).to eql("FOO" => "foo${BAR}") + expect(env("FOO=test\nBAR=\"foo\\${FOO} ${FOO}\"")).to eql("FOO" => "test", "BAR" => "foo${FOO} test") end it "parses yaml style options" do