Rubyで書いてJavaScriptで使う
AgDLRのRepl面白いですね。
CodePlex Archive
ブラウザ上で Ruby を試せる「IRBWEB」を作ってみた - てっく煮ブログ 跡地
Replは名前のとおりブラウザ上でレプるためのパーツって感じでしょうか。Replの実装は大体こんな感じでやってるんだと思います。
http://blog.tomasm.net/2009/02/20/multilingual-repl/
それを参考にして、Rubyで作ったオブジェクトをJavaScriptで利用するサンプル。
http://arikui.github.com/run_ruby/TestPage.html
オブジェクト登録後に
(なんちゃら).Invoke("呼ぶメソッドの名前", [引数])
みたいな感じでFirebugなどから呼び出してみてください。
ソース
Public Class ScriptableRuby Private Shared window As Browser.HtmlWindow = Browser.HtmlPage.Window Private Shared runtime As Microsoft.Scripting.Hosting.ScriptRuntime = IronRuby.Ruby.CreateRuntime Private Shared engine As Microsoft.Scripting.Hosting.ScriptEngine = runtime.GetEngine("IronRuby") Private Shared scope As Microsoft.Scripting.Hosting.ScriptScope = engine.CreateScope Private Shared operations As Microsoft.Scripting.Hosting.ObjectOperations = engine.CreateOperations(scope) Public Shared Function Create(ByVal source As String) Dim result = engine.Execute(source, scope) Return New RubyObject(ScriptableRuby.operations, result) End Function <Browser.ScriptableType()> _ Public Class RubyObject Private result As Object Public Sub New(ByVal operations As Microsoft.Scripting.Hosting.ObjectOperations, ByVal result As Object) Me.result = result End Sub <Browser.ScriptableMember()> _ Public Function Invoke(ByVal name As Object) As Object Return engine.Operations.Invoke(operations.GetMember(result, name)) End Function <Browser.ScriptableMember()> _ Public Function Invoke(ByVal name As Object, ByVal args As Browser.ScriptObject) As Object Dim length As Integer = args.GetProperty("length") Dim _args(length - 1) As Object For i As Integer = 0 To length - 1 _args(i) = args.GetProperty(i) Next Return engine.Operations.Invoke(operations.GetMember(result, name), _args) End Function <Browser.ScriptableMember()> _ Public Function Invoke(ByVal name As Object, ByVal ParamArray args As Object()) As Object Return engine.Operations.Invoke(operations.GetMember(result, name), args) End Function End Class End Class
ScriptableRuby.Create()は、Rubyのコードを実行して返ってきた値をJavaScriptで利用可能なScriptableRuby.RubyObjectとして返します。返ってくる値はコードの最後の行のものなので、「A.new」とか最後に書いとかないと利用できません。(そうしなくてもいい方法はあるんでしょうかね)
ScriptableRuby.RubyObjectはInvoke()でRubyのオブジェクトのメソッドを呼び出します。(サンプルではメソッドのみしか利用できません。多分)
ここで問題なのは、引数にParamArrayを指定してもJavaScript → Silverlightでちゃんと渡してくれません。なのでJavaScript側で配列として渡すことにしました。実質3つめのInvoke()は使われません。