<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Latest posts for the topic "Programando em Ruby com o Mentawai (integração total com JRuby)"]]></title>
		<link>http://recipes.mentaframework.org/posts/list/4.page</link>
		<description><![CDATA[Latest messages posted in the topic "Programando em Ruby com o Mentawai (integração total com JRuby)"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>Programando em Ruby com o Mentawai (integração total com JRuby)</title>
				<description><![CDATA[ A partir da versão 1.13 o Mentawai possui suporte total ao JRuby. Você pode escrever suas actions (e sua aplicação) inteiramente em Ruby ou você pode chamar qualquer código Ruby de dentro de suas actions em Java (ou de qualquer ponto da sua aplicação em Java).<br /> <br /> Para suportar código Ruby, tudo que você necessita é copiar o arquivo jruby.jar para dentro do /WEB-INF/lib da sua aplicação. Entretanto, se você pretende usar RubyGems ou as bibliotecas nativas do Ruby (como 'date' por exemplo) você precisará ter o JRuby instalado na máquina que está rodando o seu Tomcat. Para instalar o JRuby é muito fácil:<br /> <br /> :arrow: Baixe o arquivo zip com a instalação da última versão do JRuby aqui: http://dist.codehaus.org/jruby/ (Ex: jruby-bin-1.1.1.zip)<br /> <br /> :arrow: Extraia tudo no seu diretório raiz (ou em qualquer outro)<br /> <br /> :arrow: Sete a variável de ambiente JRUBY_HOME. (Ex: JRUBY_HOME=c:\jruby-1.1.1)<br /> <br /> :arrow: Sete a variável de ambiente JRUBY_OPTS para -rubygems. (Assim você não precisa requerer 'rubygems' nos seus códigos)<br /> <br /> :arrow: Coloque o diretório %JRUBY_HOME%\bin no seu PATH de forma que você possa executar o comando jruby de qualquer lugar.<br /> <br /> Se você fizer os passos acima você terá o jruby disponível no seu shell. Veja os exemplos abaixo:<br /> [code]<br /> c:\&gt;jruby -v<br /> ruby 1.8.6 (2008-04-22 rev 6555) [x86-jruby1.1.1]<br /> <br /> c:\&gt;jruby -S gem -v<br /> 1.1.0<br /> <br /> c:\&gt;jruby -S gem list --local<br /> <br /> *** LOCAL GEMS ***<br /> <br /> hoe (1.5.1)<br /> hpricot (0.6)<br /> jruby-openssl (0.2.3)<br /> mechanize (0.7.6)<br /> rake (0.8.1)<br /> rspec (1.1.3)<br /> rubyforge (0.4.5)<br /> sources (0.0.1)<br /> [/code]<br /> <br /> Agora vamos ao exemplo de código Ruby rodando dentro do Mentawai (baixe a versão beta do Mentawai 1.13 [url=http://www.mentaframework.org/beta/mentawai.jar]aqui[/url])<br /> <br /> Todo e qualquer código Ruby deve ficar dentro do diretório /WEB-INF/ruby da sua aplicação web. O Mentawai carrega qualquer arquivo Ruby dentro desse diretório e tb faz o reload automático em caso de modificação (como uma página JSP).<br /> <br /> Action inteiramente em Ruby: /WEB-INF/ruby/action_test.rb<br /> [code]<br /> include_class 'org.mentawai.core.BaseAction'<br /> <br /> class MyFirstRubyAction &lt; BaseAction<br />   <br />   def execute<br />     output["msg"] = "Hello from JRuby !!!!"<br />     :success<br />   end<br />   <br /> end<br /> [/code]<br /> <br /> Action em Java chamando código Ruby: /WEB-INF/src/org/hello/action/Hello.java<br /> [code]<br /> package org.hello.action;<br /> <br /> import java.util.Iterator;<br /> import java.util.Map;<br /> <br /> import org.mentawai.core.BaseAction;<br /> import org.mentawai.jruby.JRubyInterpreter;<br /> <br /> public class Hello extends BaseAction {<br /> 	<br /> 	JRubyInterpreter ruby = JRubyInterpreter.getInstance();<br /> 	<br /> 	public String execute() {<br /> 		<br /> 		Object users = ruby.eval("Users.new");<br /> 		<br /> 		Map map = (Map) ruby.call(users, "get_users");<br /> 		<br /> 		Iterator iter = map.keySet().iterator();<br /> 		<br /> 		StringBuilder sb = new StringBuilder();<br /> 		<br /> 		while(iter.hasNext()) {<br /> 			sb.append(iter.next()).append(" ");<br /> 		}<br /> 		<br /> 		output.setValue("msg", "Hello my friends: " + sb.toString());<br /> 		<br /> 		return SUCCESS;<br /> 	}<br /> }<br /> [/code]<br /> <br /> Código Ruby acessado pela action acima: /WEB-INF/ruby/users_test.rb<br /> [code]<br /> <br /> class Users<br />   <br />   def get_users<br />     a = {}<br />     a['Sergio'] = 1<br />     a['Robert'] = 2<br />     a<br />   end<br />   <br /> end<br /> [/code]<br /> <br /> ApplicationManager:<br /> [code]<br /> package org.hello;<br /> <br /> import org.hello.action.Hello;<br /> <br /> public class ApplicationManager extends org.mentawai.core.ApplicationManager {<br /> 	<br /> 	@Override<br /> 	public void loadActions() {<br /> 		<br /> 		action("/HelloRuby1", Hello.class).on(SUCCESS, "/hello.jsp");<br /> 		<br /> 		ruby("/HelloRuby2", "MyFirstRubyAction").on(SUCCESS, "/hello.jsp");<br /> 		<br /> 	}<br /> 	<br /> }<br /> [/code]<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://recipes.mentaframework.org/posts/preList/56/59.page</guid>
				<link>http://recipes.mentaframework.org/posts/preList/56/59.page</link>
				<pubDate><![CDATA[Thu, 15 May 2008 16:08:25]]> GMT</pubDate>
				<author><![CDATA[ saoj]]></author>
			</item>
			<item>
				<title>Re:Programando em Ruby com o Mentawai (integração total com JRuby)</title>
				<description><![CDATA[ Abaixo temos um resumo completo das funcionalidades do suporte a JRuby do Mentawai. (somente em inglês) (a partir da versão 1.15) ([url=http://www.mentaframework.org/beta/mentawai.jar]baixe o jar beta aqui[/url])<br /> <br /> :arrow: Simple API to call ruby methods on any Ruby object from Java<br /> :arrow: JRubyWrapper for making ruby method calls even easier<br /> :arrow: Support method chaining. Ex: "methods.sort.grep"<br /> :arrow: Auto-reload any ruby file from the loadpath<br /> :arrow: Load any ruby file from the classpath with the loadFromClasspath method<br /> :arrow: Get a singleton instance of the JRubyInterpreter anywhere in your code with the JRubyInterpreter.getInstance() method<br /> :arrow: Support all JRuby environment variables and provide defaults for them. Ex: JRUBY_OPTS for -rubygems and -Ku , JRUBY_SHELL, JRUBY_SCRIPT, JRUBY_LIB and JRUBY_HOME.<br /> :arrow: Windows and Linux support<br /> <br /> <br /> The file foo.rb anywhere in your loadpath (Ruby equivalent of Java's classpath)<br /> <br /> [color=red][b]OBS:[/b][/color] Don't forget to change this file to see how it will be automatically reloaded by JRubyInterpreter.<br /> <br /> [code]<br /> <br /> class Foo<br /> <br />     def initialize(name)<br />         @name = name<br />     end<br />     <br />     attr_accessor :name<br /> <br />     def hi<br />         puts "Hi from #{name}"<br />     end<br />     <br />     def get_a_list<br />         [1,2,3]<br />     end<br />     <br />     def get_a_hash<br />         {"one" =&gt; 1, "two" =&gt; 2}<br />     end<br />     <br />     def to_s<br />         "I am #{name}"<br />     end<br />     <br /> end<br /> [/code]<br /> <br /> Plug and play with JRubyInterpreter:<br /> <br /> [code]<br /> <br /> import org.mentawai.jruby.*;<br /> import java.util.List;<br /> import java.util.Map;<br /> <br /> public class Test {<br /> <br />     public static void main(String[] args) throws Exception {<br />         <br />         JRubyInterpreter ruby = JRubyInterpreter.getInstance();<br />         <br />         Object foo = ruby.eval("Foo.new('Sergio')"); // using eval...<br />         <br />         System.out.println("Foo class: " + foo.getClass()); // should be a RubyObject...<br />         <br />         System.out.println("Foo: " + foo); // to_s from Ruby will be called!<br />         <br />         ruby.call(foo, "hi"); // calling method hi...<br />         <br />         ruby.call(foo, "name=", "Joe"); // calling setter...<br />         <br />         ruby.call(foo, "hi"); // calling method hi...<br />         <br />         ruby.set(foo, "name", "Bill"); // shorter version for calling setter...<br />         <br />         ruby.call(foo, "hi"); // calling method hi...<br />         <br />         System.out.println("Name: " + ruby.call(foo, "name")); // calling getter...<br />         <br />         List&lt;String&gt; methods = (List&lt;String&gt;) ruby.call(foo, "methods.sort"); // method chaining...<br />         <br />         for(String s: methods) {<br />             <br />             System.out.println("M1: " + s);<br />             <br />         }<br />         <br />         methods = (List&lt;String&gt;) ruby.call(foo, "methods.sort.grep", "name="); // method chaining with params... (params only for last method!)<br />         <br />         for(String s: methods) {<br />             <br />             System.out.println("M2: " + s);<br />             <br />         }<br />         <br />         // testing respond_to?<br />         <br />         boolean ok = ruby.respondTo(foo, "get_a_list"); // calling Ruby's respond_to?...<br />         <br />         System.out.println("get_a_list: " + (ok ? "OK" : "NOTOK"));<br />         <br />         // getting a list...<br />      <br />         List&lt;Object&gt; list = (List&lt;Object&gt;) ruby.call(foo, "get_a_list");<br />         <br />         for(Object obj: list) {<br />          <br />             System.out.println(obj + " / " + obj.getClass());<br />             <br />         }<br />         <br />         // getting a hash...<br />         <br />         Map&lt;Object, Object&gt; map = (Map&lt;Object, Object&gt;) ruby.call(foo, "get_a_hash");<br />         <br />         for(Object key: map.keySet()) {<br />             <br />             Object v = map.get(key);<br />             <br />             System.out.println(key + " / " + key.getClass() + " =&gt; " + v + " / " + v.getClass());<br />         }<br />     }<br /> }<br /> [/code]<br /> <br /> Using the JRubyWrapper:<br /> <br /> [code]<br /> <br /> import org.mentawai.jruby.*;<br /> import java.util.List;<br /> import java.util.Map;<br /> <br /> public class TestWrapper {<br /> <br />     public static void main(String[] args) throws Exception {<br />         <br />         JRubyInterpreter ruby = JRubyInterpreter.getInstance();<br />         <br />         Object foo = ruby.eval("Foo.new('Sergio')"); // using eval...<br />         <br />         System.out.println("Foo class: " + foo.getClass()); // should be a RubyObject...<br />         <br />         System.out.println("Foo: " + foo); // to_s from Ruby will be called!<br />         <br />         JRubyWrapper fooW = new JRubyWrapper(foo);<br />         <br />         fooW.call("hi"); // calling method hi...<br />         <br />         fooW.call("name=", "Joe"); // calling setter...<br />         <br />         fooW.call("hi"); // calling method hi...<br />         <br />         fooW.set("name", "Bill"); // shorter version for calling setter...<br />         <br />         fooW.call("hi"); // calling method hi...<br />         <br />         System.out.println("Name: " + fooW.call("name")); // calling getter...<br /> <br />         boolean ok = fooW.respondTo("get_a_hash");<br />         <br />         System.out.println("Ok: " + ok);<br />         <br />     }<br /> }<br /> [/code]<br /> <br /> <br /> ]]></description>
				<guid isPermaLink="true">http://recipes.mentaframework.org/posts/preList/56/65.page</guid>
				<link>http://recipes.mentaframework.org/posts/preList/56/65.page</link>
				<pubDate><![CDATA[Tue, 16 Dec 2008 06:50:20]]> GMT</pubDate>
				<author><![CDATA[ saoj]]></author>
			</item>
	</channel>
</rss>