【问题标题】:Ruby insert ENV[api_key] in scriptRuby 在脚本中插入 ENV[api_key]
【发布时间】:2018-04-25 10:15:05
【问题描述】:

在 application.yml 我有api_key: 1234567890

如果我这样做(直接插入 api 键 'appid')它会起作用(小部件显示和填充):

<script>
  window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = [];  window.myWidgetParam.push({id: 15,cityid: '2643743',appid: '1234567890' %>,units: 'metric',containerid: 'openweathermap-widget-15',  });  (function() {var script = document.createElement('script');script.async = true;script.charset = "utf-8";script.src = "//openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js";var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(script, s);  })();
</script>

但如果我这样做(插入 &lt;%= ENV["api_key"] %&gt;)它不会(由于 api 键周围缺少引号,小部件不显示):

<script>
  window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = [];  window.myWidgetParam.push({id: 15,cityid: '2643743',appid: <%= ENV["api_key"] %>,units: 'metric',containerid: 'openweathermap-widget-15',  });  (function() {var script = document.createElement('script');script.async = true;script.charset = "utf-8";script.src = "//openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js";var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(script, s);  })();
</script>

我错过了什么?

【问题讨论】:

  • 该文件的名称是什么,它是如何呈现的?我打赌它的名称中没有.erb
  • home.html.erb ;)
  • 定义“不起作用”。 api 键是否正确呈现在页面上?你可能会发现你忘了添加一些东西。
  • 后续问题确实无关/超出范围。
  • @SergioTulentsev 这是否超出范围:如何隐藏 api 密钥?

标签: ruby-on-rails ruby openweathermap


【解决方案1】:

我愿意:

<%== ENV['api_key'].to_json %>

【讨论】:

  • 嗯。这会将&amp;quot;1234567890&amp;quot; 插入到脚本中!?
  • == 是与Rails' raw output helper method 等效的 ERB,它不会对输出进行 HTML 转义。
【解决方案2】:

appid: '&lt;%= ENV["api_key"] %&gt;'怎么样?

【讨论】:

  • @JohanFaerch 这不是重点吗?你说它因为缺少引号而崩溃。你的第一个例子也有appid: '1234567890',而不是appid: 1234567890
  • 在您的建议中,它将实际代码作为字符串插入,而不是 api 键。我的“第一个示例”来自具有不同语法的 yml 文件 - 不带引号。我需要在引号内传递实际的 api 密钥,如我的问题中的第一个脚本所示。
  • @JohanFaerch “只需将 作为字符串插入” - 不,我不这么认为。一定是您在应用此答案时做错了什么。
  • 对不起。误解了你的最后一部分。第一个脚本示例是正确且有效的,但在文件中直接输入了 api 密钥。
  • 从你告诉我们的情况来看,我最好的猜测是你根本不通过 erb 提供文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多