Sunday, July 18, 2010

Building a simple server/client with eventmachine 2

Following previous entry, i've come up with a drop dead simple service framework based on eventmachine, just a fun project actually, as u can see from its name "OTAKU". Since code speaks a thousand words, especially for someone like me, let's jump straight into some coding:
1
2
3
4
5
6
require 'otaku'

# Starting to otaku service
Otaku.start do |data|
result = '~ %s ~' % data
end

1
2
3
4
require 'otaku'

# client sending a process request to otaku service
Otaku.process('hello') # >> '~ hello ~'

Of course, life is never as simple as the above, since we have Otaku.start accepts a proc, most people tend to code in-a-taken-for-granted-way taking advantage of contextual references:
1
2
3
4
5
6
mark = '*'
Otaku.start do |data|
'%s %s %s' % [mark, data, mark]
end

Otaku.process('hello') # #<NameError: undefined local variable or method `mark' for ...

Now now, really unexpected rite ? The reason is that otaku converts the proc passed to Otaku.start, convert it to plain ruby code, & eval in the server process, thus, naturally, any contextual references are lost. As a workaround:
1
2
3
4
5
Otaku.start(:mark => '*') do |data|
'%s %s %s' % [mark, data, mark]
end

Otaku.process('hello') # >> '* hello *'

Well, i must admit this workaround is abit not-so-comfortable ... anyway, i'm still thinking (hard) on how the contextual references can be extracted under the hood, without having user to go through the trouble of declaring the context hash explicitely. Anyway, this is what otaku has to offer for now :]

Have a look at this slightly more complicated usage of otaku.

No comments:

Post a Comment

Labels