在 Ruby (Rails) 中评估 module.exports

Som*_*ium 5 javascript ruby ruby-on-rails execjs

目前,我正在尝试Hash从 JS 中获取某种Ruby 格式的内容。

我有一个看起来像这样的 JS 模块

module.exports = {
  key1: "val",
  key2: {
    key3: "val3"
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

这只是作为一个字符串提供给我的。我知道 ExecJS 在这里可能会有所帮助,但我不确定将其转换为哈希的最佳方法是什么。

我目前正在尝试做这样的事情

contents.prepend("var module = {exports: {}};\n")
context = ExecJS.compile contents

context.eval('module.exports').to_hash
Run Code Online (Sandbox Code Playgroud)

但是当给它一个像上面这样的字符串时,我收到了来自 JSON gem 的解析错误。

max*_*ner 1

我只是尝试将其放入脚本中并运行它:

require 'execjs'

str = <<-JS
  // Note, you could just do `var module = {}` here
  var module = {exports: {}};

  module.exports = {
    key1: "val",
    key2: {
      key3: "val3"
    }
  }
JS

context = ExecJS.compile str 
puts context.eval('module.exports').to_hash
# => {"key1"=>"val", "key2"=>{"key3"=>"val3"}}
Run Code Online (Sandbox Code Playgroud)

也许您收到 JSON 解析错误是因为该模块包含无法序列化的内容。


这是另一种方法。

创建一个加载模块并将其导出为 JSON 的 JS 文件。

var fs = require('fs');
var hash = require('path/to/my_module.js');

fs.writeFileSync('path/to/output.json', JSON.stringify(hash), 'utf8');
Run Code Online (Sandbox Code Playgroud)

运行它,nodejs my_script.js然后从 Ruby 读取它:

require 'json'
hash  = JSON.parse "path/to/output.json"
Run Code Online (Sandbox Code Playgroud)