Skip to content

Commit

Permalink
ruby-now prototype created.
Browse files Browse the repository at this point in the history
  • Loading branch information
steveWang committed Aug 5, 2011
0 parents commit 8356af6
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/namedblock.rb
@@ -0,0 +1,8 @@
class NamedBlock < Proc
def name name
@name = name
end
def to_s
@name
end
end
37 changes: 37 additions & 0 deletions lib/ruby-now.rb
@@ -0,0 +1,37 @@
# A ruby newbie am I!

require 'eventmachine'
require 'json'
require 'util'
require 'namedblock'

module BidirectionalJsonRadio
@@conn = []
def self.conn
@@conn
end
def self.registerFunction name, block
Util.registerFunction name, block
end
def initialize
@@conn.push self
end
def post_init
send_data Util.functions.keys.to_json
end
def receive_data data
Util.processData(JSON.parse data)
end
def unbind
@@conn.delete self
end
end

EventMachine::run {
EventMachine::start_server "127.0.0.1", 8081, BidirectionalJsonRadio
BidirectionalJsonRadio.registerFunction('aFunctionObject', lambda{|*a|
puts a.join(' ')})
BidirectionalJsonRadio.registerFunction('otherFunc', lambda{|cb, *a|
cb.call(a.join(' '))})
puts 'running json radio of happiness on port 8081 of your microwave'
}
43 changes: 43 additions & 0 deletions lib/util.rb
@@ -0,0 +1,43 @@
module Util
@@closures = {}
@@functions = {}

def self.functions
@@functions
end
def self.registerFunction name, block
block = NamedBlock.new(&block)
block.name name
@@functions[name] = block
end
def self.processData hash
obj = hash['args'][0];
case hash['name']
when 'rfc'
self.callFunc(@@functions[obj['fqn']], obj['args'])
else
puts 'unidentified json, json'
end
end

def self.callFunc func, args
func.call *(args.collect{|a|
((a.is_a?(Hash) && a.has_key?('fqn')) ?
(@@functions.has_key?(a['fqn']) ?
@@functions[a['fqn']] :
(@@closures.has_key?(a['fqn']) ?
@@closures[a['fqn']] :
(lambda{|*args|
self.send_data({ "name" => "rfc",
"args" => [{ "fqn" => a['fqn'],
"args" => args }] }.to_json) }))) :
(a.is_a?(Proc) ?
(((@@closures[a.to_s] = a) && true) ||
{"fqn" => a.to_s}) :
a))
})
end
def self.send_data str
BidirectionalJsonRadio.conn[0].send_data str
end
end
21 changes: 21 additions & 0 deletions ruby-now.gemspec
@@ -0,0 +1,21 @@
require 'eventmachine'
Gem::Specification.new do |s|
s.name = 'n00by'
s.version = '0.0.1'
s.homepage = 'http://nowjs.org'

s.authors = ["Flotype"]
s.email = ["team@nowjs.org"]

s.files = `git ls-files`.split("\n")

s.add_dependency('eventmachine', '>= 1.0.0.beta.1')
s.add_dependency('json', '>= 1.5.0')

s.summary = 'Ruby/NowJS library'

s.description = "n00by is a Ruby interface for NowJS, designed to be
used as the layer of communication between a Node server running
NowJS and a Rails server running whatever Ruby app you might have."

end

0 comments on commit 8356af6

Please sign in to comment.