Skip to content

Commit 608e4cb

Browse files
committed
add calling erlang from Rails example
1 parent 4bcf4bb commit 608e4cb

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

README.textile

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,79 @@ end
5252
</code>
5353
</pre>
5454

55+
56+
h3. So you wanna call Erlang from your Rails app...
57+
58+
Here's a quick and simple example. Make sure you put the rinterface lib into RAILS_ROOT/lib and start the math_server in 'test'
59+
60+
First we'll wrap rinterface in a class to call from Rails:
61+
62+
models/math_service.rb
63+
64+
<pre>
65+
<code>
66+
require 'lib/rinterface'
67+
68+
class MathService
69+
include Erlang
70+
attr_accessor :result
71+
72+
def self.sum(args)
73+
s = self.new
74+
s.call_erlang(args)
75+
s.result
76+
end
77+
78+
def initialize
79+
@result = 0
80+
end
81+
82+
def call_erlang(args)
83+
EM.run do
84+
# Connect to epmd to get the port of 'math'.
85+
# 'math' is the -sname of the erlang node
86+
epmd = EpmdConnection.lookup_node("math")
87+
epmd.callback do |port|
88+
89+
# make the rpc call to 'math' on port for mod 'math_server' on
90+
# fun 'add' with args
91+
node = Node.rpc_call("math",port.to_i,"math_server","add",args)
92+
node.callback{ |result|
93+
@result = result
94+
EM.stop
95+
}
96+
97+
node.errback{ |err|
98+
EM.stop
99+
}
100+
end
101+
102+
epmd.errback do |err|
103+
EM.stop
104+
end
105+
end
106+
end
107+
108+
end
109+
</code>
110+
</pre>
111+
112+
Now here's the controller:
113+
114+
controllers/math_controller.rb
115+
116+
<pre>
117+
<code>
118+
class MathController < ApplicationController
119+
def index
120+
a = params[:a]
121+
b = params[:b]
122+
@result = MathService.sum([a.to_i,b.to_i])
123+
end
124+
end
125+
</code>
126+
</pre>
127+
128+
Finally, add a template for the view, and try 'http://localhost:3000/math?a=2&b=3'.
129+
130+
This is not ideal yet and not something I'd use yet in production, but it's a starting point for experimenting.

0 commit comments

Comments
 (0)