Joe Williams home
Looking for ways to have Erlang and other languages inter-operate I found Erlectricity. It is a ruby library (gem install erlectricity) that assists in message passing between Erlang and Ruby. Electricity basically allows Ruby and Erlang to talk using an Erlang port to a Ruby process. I checked out a couple of the examples contained in the source and decided to expand upon the echo program. My version takes a tuple, the first item being what job to do and the second is a URL. Erlang determines what to send along to Ruby, sends it and Ruby runs either job and returns the result. The two options are scrape and url, the first will scrape the URL provided and return the HTML the latter will simply return the URL you provided to it. The Erlang side:
-module(echo). -export([job/1]). job(Info) -> Cmd = "ruby webscrape.rb", Port = open_port({spawn, Cmd}, [{packet, 4}, use_stdio, exit_status, binary]), case Info of {scrape, Site} -> Payload = term_to_binary({scrape, Site}), port_command(Port, Payload); {url, Site} -> Payload = term_to_binary({url, Site}), port_command(Port, Payload); Error -> Error end, receive {Port, {data, Data}} -> {result, Text} = binary_to_term(Data), io:format("~p~n", [Text]) end.
The Ruby side:
require 'net/http' require 'rubygems' require 'erlectricity' require 'stringio' receive do |f| f.when(:scrape, String) do |text| scrape = Net::HTTP.get_response(URI.parse(text)) f.send!(:result, scrape.body) f.receive_loop end f.when(:url, String) do |text| f.send!(:result, "You gave #{text}") f.receive_loop end end
Here's an example of its usage:
10> echo:job({url, <<"http://www.joetify.com">>}). <<"You gave http://www.joetify.com">> ok 11> echo:job({scrape, <<"http://www.joetify.com">>}). <<"html>ncenter>nimg src="./joetify_logo.png">ncenter>nhtml>n">> ok
I modified the HTML code so it shows up properly above. Pretty cool stuff. If you find this interesting you should certainly check out fuzed, a Yaws based web server that allows you to run Ruby on Rails apps behind it. I have played with it a bit and the clustering of rails nodes is pretty sweet.
Fork me on GitHub