Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating module.exports in Ruby (Rails)

Currently I'm looking to try to get something in a Hash format in Ruby from JS.

I have a JS module that looks something like this

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

This is given to me as just one string. I'm aware that ExecJS could be helpful here but I'm not sure what the best way to convert it to a Hash would be.

I'm currently trying to do something like this

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

context.eval('module.exports').to_hash

But when giving it a string like above I'm getting a parsing error from the JSON gem.

like image 999
Somnium Avatar asked Nov 06 '22 01:11

Somnium


1 Answers

I just tried putting this in a script and running it:

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"}}

Maybe you're getting the JSON parse error because the module contains something which can't be serialized.


Here's another approach.

Make a JS file which loads the module and exports it as JSON.

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

fs.writeFileSync('path/to/output.json', JSON.stringify(hash), 'utf8');

Run that with nodejs my_script.js then read it from Ruby:

require 'json'
hash  = JSON.parse "path/to/output.json"
like image 187
max pleaner Avatar answered Nov 11 '22 04:11

max pleaner