Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Last active April 26, 2024 23:26
Show Gist options
  • Save sasa1977/d862a8107071651b34d0 to your computer and use it in GitHub Desktop.
Save sasa1977/d862a8107071651b34d0 to your computer and use it in GitHub Desktop.
cmd = ~S"""
ruby -e '
require "bundler"
require "erlang/etf"
require "stringio"
@input = IO.new(3)
@output = IO.new(4)
@output.sync = true
def receive_input
encoded_length = @input.read(4)
return nil unless encoded_length
length = encoded_length.unpack("N").first
Erlang.binary_to_term(@input.read(length))
end
def send_response(value)
response = Erlang.term_to_binary(Erlang::Tuple[:response, value])
@output.write([response.length].pack("N"))
@output.write(response)
true
end
context = binding
while (cmd = receive_input) do
if cmd.is_a?(Erlang::Tuple) && cmd[0] == :eval
puts "Ruby: #{cmd[1]}"
res = eval(cmd[1], context)
puts "Ruby: => #{res.inspect}\n\n"
end
end
puts "Ruby: exiting"
'
"""
send_eval = fn(port, command) ->
Port.command(port, :erlang.term_to_binary({:eval, command}))
end
port = Port.open({:spawn, cmd}, [:binary, {:packet, 4}, :nouse_stdio])
send_eval.(port, "a = 1")
send_eval.(port, ~S"""
while a < 10 do
a *= 3
end
""")
send_eval.(port, "send_response(a)")
receive do
{^port, {:data, result}} ->
IO.puts("Elixir got: #{inspect :erlang.binary_to_term(result)}")
end
Port.close(port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment