Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created August 29, 2010 04:05
Show Gist options
  • Save leandrosilva/555946 to your computer and use it in GitHub Desktop.
Save leandrosilva/555946 to your computer and use it in GitHub Desktop.
Erlectricity sample (Erlang <-> Ruby)
This sample is strongly based on Erlectricity, avaliable from:
http://github.com/mojombo/erlectricity
The echo.rb is the same, but the echo.erl is really a little bit better. It's because I refactored it to
extract functions to send and receive messages and also (and more important) introduce some patterns on
receive statement to matching other messages (specially to receive exit_status messages from "dead" ports).
More sugar is always good. At least for me. ;)
-module(echo).
-export([say/0]).
say() ->
Command = "ruby echo.rb",
Port = open_port({spawn, Command}, [{packet, 4}, nouse_stdio, exit_status, binary]),
Message = term_to_binary({echo, <<"A message from Erlang to Ruby">>}),
send_to(Port, Message),
receive_from(Port).
send_to(Port, Message) ->
port_command(Port, Message).
receive_from(Port) ->
receive
{Port, {data, Data}} ->
{response, Text} = binary_to_term(Data),
io:format("echoed message >> ~p~n", [Text]);
{DeadPort, {exit_status, Number}} ->
io:format("exit message >> dead port: ~p | status: ~p~n", [DeadPort, Number]),
receive_from(Port);
Unrecognized ->
io:format("unrecognized message >> ~p~n", [Unrecognized])
end.
require 'rubygems'
require 'erlectricity'
receive do |f|
f.when([:echo, String]) do |text|
f.send!([:response, "Received message: #{text}"])
f.receive_loop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment