2

I have an environment variable along the lines of:

MY_VALUE: "EFINbA\u003d\u003d\n"

When I read it through ruby it is returned as:

ENV['MY_VALUE']
=> "EFINbA\\u003d\\u003d\\n"

... but only on Heroku, not on Mac (where it was set through a local_env.yml file, admittedly)

So first of all, I just don't understand why it is doing that.

Secondly, when I attempt to remove the \ and replace them with \, I have found nothing that works.

Although: ENV['MY_VALUE'].gsub("\","x") => "EFINbAxu003dxu003dxn"

This: ENV['MY_VALUE'].gsub("\","\")

... doesn't work because the last double-quote is escaped, while:

ENV['MY_VALUE'].gsub("\\","\\")

... effectively does nothing at all.

Evidently I am missing something basic here, and it's too late in the day for me to spot it.

Thanks.

David Aldridge
  • 51,479
  • 8
  • 68
  • 96

2 Answers2

3

You can try YAML's unescape

require 'yaml'

def unescape(s)
    YAML.load(%Q(---\n"#{s}"\n))
end

unescape(ENV['MY_VALUE'])

or if you don't bring in the yaml module you can use eval

def unescape(s)
    eval %Q{"#{s}"}
end

The advantage to YAML over eval is that it is presumably safer.

blackmind
  • 1,286
  • 14
  • 27
0

YAML.safe_load sometimes changes characters in the env string - so it is not an optimal solution.

As eval is also not the solution as it is not that safe, .undump was the answer I was looking for.

Maxeezy
  • 39
  • 1
  • 6