当前位置: 动力学知识库 > 问答 > 编程问答 >

Ruby on Rails 4 on Heroku, Environment variables with backslash escape

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: