Shopify / schmooze

Schmooze lets Ruby and Node.js work together intimately.
MIT License
72 stars 16 forks source link

Is it possible to modify an object that is passed as an argument and get it back on Ruby? #16

Open cirosantilli opened 5 years ago

cirosantilli commented 5 years ago

Doesn't seem so:

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  method :version, 'function(mydict) { mydict["b"] = 2}'
end
babel = BabelSchmoozer.new(__dir__)
mydict = { 'a': 1 }
babel.version(mydict)
puts mydict

outputs:

{:a=>1}

But I found a reasonable workaround, which is to pass the value back on the return, and use an array of return values if I need more than one return object:

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  method :version, 'function(mydict) { mydict["b"] = 2; return mydict}'
end
babel = BabelSchmoozer.new(__dir__)
mydict = { 'a': 1 }
mydict = babel.version(mydict)
puts mydict

outputs:

{"a"=>1, "b"=>2}

and if the goal is to preserve a state parameter across calls, you can use the global object itself!

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  dependencies babel: 'babel-core'

  method :init, 'function() { babel.cirosantilli_mydict = []; }'
  method :version, 'function(val) { babel.cirosantilli_mydict.push(val); return babel.cirosantilli_mydict; }'
end
babel = BabelSchmoozer.new(__dir__)
babel.init
puts babel.version(0)
puts babel.version(1)

Tested on schmooze (0.2.0).