<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>jruby &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/jruby/</link>
	<description>Feed of posts on WordPress.com tagged "jruby"</description>
	<pubDate>Fri, 04 Dec 2009 11:54:29 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[More Oracle data types supported by ruby-plsql gem]]></title>
<link>http://blog.rayapps.com/2009/11/25/more-oracle-data-types-supported-by-ruby-plsql-gem/</link>
<pubDate>Wed, 25 Nov 2009 14:34:33 +0000</pubDate>
<dc:creator>Raimonds Simanovskis</dc:creator>
<guid>http://blog.rayapps.com/2009/11/25/more-oracle-data-types-supported-by-ruby-plsql-gem/</guid>
<description><![CDATA[I have just released ruby-plsql gem version 0.4.0 which provides many new features. You can read abo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I have just released <a href="http://github.com/rsim/ruby-plsql">ruby-plsql</a> gem version 0.4.0 which provides many new features. You can read about initial versions of ruby-plsql in <a href="http://blog.rayapps.com/category/plsql/">previous blog posts</a>.</p>
<h3>Oracle complex data type support</h3>
<p>Initial versions of ruby-plsql supported just simple Oracle types like NUMBER, VARCHAR2, DATE, TIMESTAMP, CLOB, BLOB as PL/SQL procedure parameters. Now support for many more complex data types is added. See examples below how to call PL/SQL procedures with these complex data types.</p>
<h4>PL/SQL Record</h4>
<p>Let&#8217;s assume you have PL/SQL procedure with PL/SQL record type parameter (which most typically will be in table%ROWTYPE format):</p>
<pre>
CREATE TABLE test_employees (
          employee_id   NUMBER(15),
          first_name    VARCHAR2(50),
          last_name     VARCHAR2(50),
          hire_date     DATE
        );
CREATE OR REPLACE FUNCTION test_full_name (p_employee test_employees%ROWTYPE)
RETURN VARCHAR2 IS
BEGIN
  RETURN p_employee.first_name &#124;&#124; ' ' &#124;&#124; p_employee.last_name;
END;
</pre>
<p>Then you can create Ruby Hash with record field values (specifying field names as Symbols), e.g.:</p>
<pre>
p_employee = {
  :employee_id =&#62; 1,
  :first_name =&#62; 'First',
  :last_name =&#62; 'Last',
  :hire_date =&#62; Time.local(2000,01,31)
}
</pre>
<p>and pass this Hash as a parameter which will be translated to PL/SQL record parameter by ruby-plsql:</p>
<pre>
plsql.test_full_name(p_employee) #=&#62; "First Last"
# or
plsql.test_full_name(:p_employee =&#62; p_employee) #=&#62; "First Last"
</pre>
<p>In the same way you can get PL/SQL function return values or output parameter values as Hash values.</p>
<h4>Object type</h4>
<p>In similar way also object type parameters can be passed as Hash values. In this case also nested objects or nested collections of objects are supported:</p>
<pre>
CREATE OR REPLACE TYPE t_address AS OBJECT (
  street    VARCHAR2(50),
  city      VARCHAR2(50),
  country   VARCHAR2(50)
);
CREATE OR REPLACE TYPE t_phone AS OBJECT (
  type            VARCHAR2(10),
  phone_number    VARCHAR2(50)
);
CREATE OR REPLACE TYPE t_phones AS TABLE OF T_PHONE;
CREATE OR REPLACE TYPE t_employee AS OBJECT (
  employee_id   NUMBER(15),
  first_name    VARCHAR2(50),
  last_name     VARCHAR2(50),
  hire_date     DATE,
  address       t_address,
  phones        t_phones
);
CREATE OR REPLACE FUNCTION test_full_name (p_employee t_employee)
  RETURN VARCHAR2
IS
BEGIN
  RETURN p_employee.first_name &#124;&#124; ' ' &#124;&#124; p_employee.last_name;
END;
</pre>
<p>and from Ruby side you can call this PL/SQL function as:</p>
<pre>
p_employee = {
  :employee_id =&#62; 1,
  :first_name =&#62; 'First',
  :last_name =&#62; 'Last',
  :hire_date =&#62; Time.local(2000,01,31),
  :address =&#62; {:street =&#62; 'Main street 1', :city =&#62; 'Riga', :country =&#62; 'Latvia'},
  :phones =&#62; [{:type =&#62; 'mobile', :phone_number =&#62; '123456'}, {:type =&#62; 'home', :phone_number =&#62; '654321'}]
}
plsql.test_full_name(p_employee) #=&#62; "First Last"
# or
plsql.test_full_name(:p_employee =&#62; p_employee) #=&#62; "First Last"
</pre>
<p>And also object type return values and output parameters will be returned as Ruby Hash values (with nested Hashes or Arrays if necessary).</p>
<p>There is one limitation that these object types should be defined as database types and not just inside PL/SQL package definition. Unfortunately you cannot access type definitions inside packages from OCI or JDBC drivers and as a result cannot call such procedures from outside of PL/SQL.</p>
<h4>TABLE and VARRAY collections</h4>
<p>TABLE and VARRAY collection parameters can be passed as Array values:</p>
<pre>
CREATE OR REPLACE TYPE t_numbers AS TABLE OF NUMBER(15);
CREATE OR REPLACE FUNCTION test_sum (p_numbers IN t_numbers)
  RETURN NUMBER
IS
  l_sum   NUMBER(15) := 0;
BEGIN
  IF p_numbers.COUNT &#62; 0 THEN
    FOR i IN p_numbers.FIRST..p_numbers.LAST LOOP
      IF p_numbers.EXISTS(i) THEN
        l_sum := l_sum + p_numbers(i);
      END IF;
    END LOOP;
    RETURN l_sum;
  ELSE
    RETURN NULL;
  END IF;
END;
</pre>
<p>And from Ruby side:</p>
<pre>
plsql.test_sum([1,2,3,4]) #=&#62; 10
</pre>
<h4>CURSOR</h4>
<p>You can get also cursor return values from PL/SQL procedures:</p>
<pre>
CREATE OR REPLACE FUNCTION test_cursor
  RETURN SYS_REFCURSOR
IS
  l_cursor  SYS_REFCURSOR;
BEGIN
  OPEN l_cursor FOR
  SELECT * FROM test_employees ORDER BY employee_id;
  RETURN l_cursor;
END;
</pre>
<p>can be called from Ruby in the following way:</p>
<pre>
plsql.test_cursor do &#124;cursor&#124;
  cursor.fetch #=&#62; first row from test_employees will be returned
end
</pre>
<p>It is important to pass block parameter in this case and do something with returned cursor within this block as after ruby-plsql finishes PL/SQL procedure call it will close all open cursors and therefore it will not be possible to do anything with returned cursor outside this block.</p>
<p>It is also possible to use returned cursor as input parameter for another PL/SQL procedure:</p>
<pre>
CREATE OR REPLACE FUNCTION test_cursor_fetch(p_cursor SYS_REFCURSOR)
  RETURN test_employees%ROWTYPE
IS
  l_record  test_employees%ROWTYPE;
BEGIN
  FETCH p_cursor INTO l_record;
  RETURN l_record;
END;
</pre>
<pre>
plsql.test_cursor do &#124;cursor&#124;
  plsql.test_cursor_fetch(cursor) #=&#62; first record as Hash
end
</pre>
<p><strong>Note</strong>: you can pass cursors as PL/SQL procedure input parameter just when using ruby-plsql on MRI 1.8/1.9 with ruby-oci8, unfortunately I have not found a way how to pass cursor as input parameter when using JRuby and JDBC.</p>
<h4>BOOLEAN</h4>
<p>And finally you can use also PL/SQL BOOLEAN type &#8211; it is quite tricky data type as it is supported just by PL/SQL but not supported as data type in Oracle tables. But now you can also use it with ruby-plsql:</p>
<pre>
CREATE OR REPLACE FUNCTION test_boolean
  ( p_boolean BOOLEAN )
  RETURN BOOLEAN
IS
BEGIN
  RETURN p_boolean;
END;
</pre>
<pre>
plsql.test_boolean(true) #=&#62; true
</pre>
<p>You can find more PL/SQL procedure call usage examples in <a href="http://github.com/rsim/ruby-plsql/blob/master/spec/plsql/procedure_spec.rb">ruby-plsql RSpec tests</a>.</p>
<h3>Table and sequence operations</h3>
<p>I have been using and promoting to others ruby-plsql as PL/SQL procedure unit testing tool. As current PL/SQL unit testing tools are not so advanced and easy to use as Ruby unit testing tools then I like better to use Ruby testing tools (like RSpec) together with ruby-plsql to write short and easy to understand PL/SQL unit tests.</p>
<p>In unit tests in setup and teardown methods you typically need some easy way how to create some sample data in necessary tables as well as to validate resulting data in tables after test execution.</p>
<p>If you are Ruby on Rails developer then you probably will use ActiveRecord (or DataMapper) for manipulation of table data. But if Ruby is used just for unit tests then probably ActiveRecord would be too complicated for this task.</p>
<p>Therefore I added some basic table operations to ruby-plsql which might be useful e.g. in unit tests. Some syntax ideas for these table operations are coming from <a href="http://github.com/jeremyevans/sequel/">Sequel</a> Ruby library.</p>
<h4>INSERT</h4>
<pre>
# insert one record
employee = { :employee_id =&#62; 1, :first_name =&#62; 'First', :last_name =&#62; 'Last', :hire_date =&#62; Time.local(2000,01,31) }
plsql.employees.insert employee # INSERT INTO employees VALUES (1, 'First', 'Last', ...)
</pre>
<pre>
# insert many records
employees = [employee1, employee2, ... ]  # array of many Hashes
plsql.employees.insert employees
</pre>
<p>If primary key values should be selected from sequence then you can get next sequence values with</p>
<pre>
plsql.employees_seq.nextval # SELECT employees_seq.NEXTVAL FROM dual
plsql.employees_seq.currval # SELECT employees_seq.CURRVAL FROM dual
</pre>
<h4>SELECT</h4>
<pre>
# select one record
plsql.employees.first # SELECT * FROM employees
                      # fetch first row =&#62; {:employee_id =&#62; ..., :first_name =&#62; '...', ...}
plsql.employees.first(:employee_id =&#62; 1)  # SELECT * FROM employees WHERE employee_id = 1
plsql.employees.first("WHERE employee_id = 1")
plsql.employees.first("WHERE employee_id = :employee_id", 1)
# select many records
plsql.employees.all                       # =&#62; [{...}, {...}, ...]
plsql.employees.all(:order_by =&#62; :employee_id)
plsql.employees.all("WHERE employee_id &#62; :employee_id", 5)
</pre>
<pre>
# count records
plsql.employees.count                     # SELECT COUNT(*) FROM employees
plsql.employees.count("WHERE employee_id &#62; :employee_id", 5)
</pre>
<h4>UPDATE</h4>
<pre>
# update records
plsql.employees.update(:first_name =&#62; 'Second', :where =&#62; {:employee_id =&#62; 1})
                      # UPDATE employees SET first_name = 'Second' WHERE employee_id = 1
</pre>
<h4>DELETE</h4>
<pre>
# delete records
plsql.employees.delete(:employee_id =&#62; 1) # DELETE FROM employees WHERE employee_id = 1
</pre>
<h4>Other SQL statements</h4>
<p>Any other SELECT statement can be executed with</p>
<pre>
plsql.select :first, "SELECT ..."
# or
plsql.select :all, "SELECT ..."
</pre>
<p>or any other non-SELECT SQL statement can be executed with</p>
<pre>
plsql.execute "..."
</pre>
<p>And also COMMIT or ROLLBACK could be executed simply with</p>
<pre>
plsql.commit
plsql.rollback
</pre>
<p>I plan to write a separate blog post about how I recommend to create PL/SQL unit tests using Ruby and ruby-plsql and RSpec.</p>
<h3>Install</h3>
<p>As always you can install latest version of ruby-plsql with</p>
<pre>
gem install ruby-plsql
</pre>
<p>Latest gem version is just on <a href="http://gemcutter.org/gems/ruby-plsql">Gemcutter</a> but now it should be available as default gem source for all Ruby installations.</p>
<p>And as always ruby-plsql is supported both on</p>
<ul>
<li>Ruby 1.8.6/1.8.7 or Ruby 1.9.1 with ruby-oci8 gem version 2.0.3 or later (some specific issues with complex data types will be fixed in later versions of ruby-oci8)</li>
<li>JRuby 1.3/1.4 with Oracle JDBC driver (testing mainly with ojdbc14.jar but also ojdbc5.jar or ojdbc6.jar should be fine)</li>
</ul>
<p>Please try it out and tell me if there are any issues with some particular data types or if there are still some unsupported PL/SQL data types that you would like to be supported in ruby-plsql. And also I encourage you to try ruby-plsql out for PL/SQL unit testing if you had no PL/SQL unit tests previously <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Installing #jruby on #rails on #torquebox]]></title>
<link>http://jrubyist.wordpress.com/2009/11/23/installing-jruby-on-rails-on-torquebox/</link>
<pubDate>Mon, 23 Nov 2009 23:53:39 +0000</pubDate>
<dc:creator>jrubyist</dc:creator>
<guid>http://jrubyist.wordpress.com/2009/11/23/installing-jruby-on-rails-on-torquebox/</guid>
<description><![CDATA[There are lots of options available for deploying #juby on #rails apps, from glassfish, to mongrel, ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>There are lots of options available for deploying #juby on #rails apps, from glassfish, to mongrel, to jboss.  Along came an excellent solution for #jruby on #rails developers called #torquebox.  It&#8217;s an enterprise level deployment environment for #jruby on #rails apps built ontop of #jboss, with several nice features built into it.  These currently include support for job scheduling outside of cron that actually deploys with your application, task queues built on top of JMS topics, and even SOAP &#38; SIP (telecom) integration.</p>
<p>Torquebox can be installed two different ways:<br />
1) Download the entire #torquebox package and follow the instructions on <a href="http://torquebox.org">torquebox.org</a>.  This includes jruby, JBoss AS 5 and torquebox gems and jars for deploying apps.<br />
2) Modify an existing JBoss AS 5 with a single jar.</p>
<p>Since most users of ruby on rails already have some version of ruby on their system, but most don&#8217;t have jboss, I&#8217;ll provide an easy way to get started with option #1.  I know this is only a small contribution back to the j/ruby community, but I think it will help provide the lowest cost to entry for most #ruby on #rails developers wishing to transition to a stable #jruby on #rails deployment environment.</p>
<p>To help get you started, I&#8217;ve put together a script to download #torquebox, unzip it, add a symlink, append the .bash_profile, &#38; install jruby-openssl.<br />
I put together a script to download #torquebox, unzip it, add a symlink, append the .bash_profile, &#38; install jruby-openssl.</p>
<pre>
require 'rubygems'
require 'net/http'
require 'logger'

class TorqueboxInstaller

  def initialize( torquebox_version = '1.0.0.Beta18' )
    @torquebox_version = torquebox_version
    yield self if block_given?
  end

  def download
    if File.exist?( torquebox_zip_file )
      logger.info "#{torquebox_zip_file} already exists."
    else
      logger.info "About to download #{torquebox_zip_file}..."
      uri = "http://repository.torquebox.org/maven2/releases" +
               "/org/torquebox/torquebox-bin/" +
              "#{@torquebox_version}/#{torquebox_zip_file}"
      `curl #{uri} -O #{torquebox_zip_file}`
      logger.info "Downloading of #{torquebox_zip_file} complete."
    end
  end

  def unzip
    if File.exist?( "#{torquebox_directory}" )
      logger.info "#{torquebox_directory} already exists.  Not unzipping."
    else
      logger.info "Unzipping #{torquebox_zip_file}"
      `unzip #{torquebox_zip_file}`
    end
  end

  def symlink
    logger.info "Creating symlink torquebox-current " +
         " for #{torquebox_directory}"
    `rm torquebox-current` if File.exist?( "torquebox-current" )
    `ln -s #{torquebox_directory}/ torquebox-current`
  end

  def append_bash_profile
    logger.info "Append the bash profile"
    File.open("#{ENV['HOME']}/.bash_profile", "a") do &#124;file&#124;
      file.puts("# environment variables for torquebox ")
      file.puts("export TORQUEBOX_HOME=#{ENV['PWD']}" +
                                "/#{torquebox_directory}")
      file.puts("export JRUBY_HOME=$TORQUEBOX_HOME/jruby")
      file.puts("export JBOSS_HOME=$TORQUEBOX_HOME/jboss")
      file.puts("export PATH=$TORQUEBOX_HOME/bin:" +
                    "$JRUBY_HOME/bin:$JBOSS_HOME/bin:$PATH")
    end
  end

  def install_dependencies
    logger.info "Installing SSL support"
    exec "source ~/.bash_profile &#38;&#38; jruby -S gem install jruby-openssl"
  end

  def torquebox_zip_file
    torquebox_zip_file = "torquebox-bin-#{@torquebox_version}.zip"
  end

  def torquebox_directory
    "torquebox-#{@torquebox_version}-bin"
  end

  def logger
    @logger &#124;&#124;= Logger.new( STDOUT )
  end
end

TorqueboxInstaller.new do &#124;installer&#124;
  installer.download
  installer.unzip
  installer.symlink
  installer.append_bash_profile
  installer.install_dependencies
end
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Usando frameworks Java com JRuby]]></title>
<link>http://mauricioszabo.wordpress.com/2009/11/18/usando-frameworks-java-com-jruby/</link>
<pubDate>Wed, 18 Nov 2009 12:49:25 +0000</pubDate>
<dc:creator>Maurício Szabo</dc:creator>
<guid>http://mauricioszabo.wordpress.com/2009/11/18/usando-frameworks-java-com-jruby/</guid>
<description><![CDATA[Estes dias, estava vendo uns projetos antigos e lembrei de um framework bem legal para Java chamado ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Estes dias, estava vendo uns projetos antigos e lembrei de um framework bem legal para Java chamado ZK. O problema do ZK é que você consegue aproveitar o máximo dele quando você programa usando Servlets, e não usando o modelo ZUL dele. Lembrei de alguns projetos que fiz, de algumas coisas interessantes que ele fazia e também lembrei que eu cheguei a programar com Servlet em Ruby, e aqui vai como eu fiz mais esse trabalho para evitar Java. <strong>NOTA:</strong> Isso funciona com qualquer framework Java, seja ele ZK ou Echo2 ou qualquer outro, porque na verdade o que você faz é escrever algumas linhas de código de &#8220;cola&#8221; e depois passa o controle para o JRuby</p>
<p>A primeira coisa que você precisa é do JRuby instalado, e de um compilador Java. Crie seu projeto normalmente, e provavelmente você terá uma classe que será responsável por instanciar a primeira classe (janela, página, seja lá o que for) do seu Servlet. Nesse ponto que a &#8220;mágica&#8221; acontece. Para simplificar as coisas, que vou criar uma classe (chamada Inicial) que instanciará uma JFrame. Toda a JFrame será definida em JRuby.</p>
<p><!--more--></p>
<p><strong>O processo:</strong> Basicamente, o que faremos é o seguinte: Criaremos uma classe abstrata (Janela), e nesta classe criaremos uma função, que será usada pelo JRuby. Na classe de &#8220;cola&#8221;, instanciaremos um interpretador JRuby, rodaremos um código para instanciar a classe do Ruby e faremos um &#8220;casting&#8221; desse objeto para a classe abstrata. Primeiro, a classe abstrata:</p>
<pre>Arquivo Janela.java:
<pre class="brush: java;">
import javax.swing.*;

public abstract class Janela extends JFrame {
        public abstract void exibir();
}
</pre>
</pre>
<p>Até aqui, nenhum segredo. A classe extende JFrame (quando você for usar seu Framework, ela deverá extender a &#8220;Window&#8221; do seu framework) e possui um método abstrato &#8220;exibir&#8221;. Agora, a classe em JRuby</p>
<pre>Arquivo ruby/janela.rb
<pre class="brush: ruby;">
java_import 'javax.swing.JFrame'
java_import 'javax.swing.JButton'
java_import 'javax.swing.JOptionPane'

class Janela &#60; Java::Janela
  def exibir
    set_size 300, 200

    self.default_close_operation = JFrame::EXIT_ON_CLOSE
    self.title = 'Uma janela qualquer'
    show

    puts &#34;Exibi uma janela!!!&#34;
  end
end
</pre>
</pre>
<p>Caso você não esteja acostumado com JRuby usando Swing, ignore os detalhes da implementação. O que é importante é pensar que você está criando uma classe JRuby, que herda de Java::Janela (a janela que definimos no Java), e cria um método &#8220;exibir&#8221;. Agora, vem o código mais complicado, a classe Inicial que instanciará a classe Ruby:</p>
<pre>Arquivo Inicial.java:
<pre class="brush: java;">
import java.util.*;
import org.jruby.*;
import org.jruby.javasupport.*;
import org.jruby.runtime.builtin.*;

public class Inicial {
    public static void main(String[] args) {
        Ruby rubyRuntime;

        //Inicia os &#34;load paths&#34;, para indicar aonde o JRuby procurará os &#34;require&#34;s
        List&#60;String&#62; pathsLoad = new ArrayList&#60;String&#62;();
        pathsLoad.add(&#34;ruby/&#34;);
        pathsLoad.add(&#34;ruby/lib&#34;);

        //Instancia os serviços do JRuby
        rubyRuntime = JavaEmbedUtils.initialize(pathsLoad);
        //Carrega o arquivo &#34;janela.rb&#34;
        rubyRuntime.getLoadService().load(&#34;janela.rb&#34;, false);

        //Roda um comando JRuby, e captura o resultado
        Object janela_rb = rubyRuntime.evalScriptlet(&#34;Janela.new&#34;);
        //Transforma na classe abstrata
        Janela janela = (Janela)JavaEmbedUtils.rubyToJava(rubyRuntime,
                                 (IRubyObject) janela_rb, Janela.class);

        janela.exibir();
    }
}
</pre>
</pre>
<p>Aqui, a mágica acontece: Cria-se um rubyRuntime, cria-se uma lista com os loadPaths (aonde o Ruby buscará os &#8220;require&#8221;s, que no meu caso eu destinei para a pasta &#8220;ruby&#8221; e &#8220;ruby/lib&#8221;. Então, instancia-se o rubyRuntime, pede-se para ele carregar o arquivo &#8220;janela.rb&#8221;, roda-se um comando bem simples (&#8220;Janela.new&#8221;) e captura o resultado, depois convertemos isso para uma classe Java. Como não temos uma definição de classe mesmo para Ruby, fazemos um &#8220;casting&#8221; para o Janela (classe abstrata no Java) e então finalmente rodamos o código &#8220;exibir&#8221;. Aparentemente, as novas versões do JRuby tornarão isso mais fácil porque permitirão que os códigos JRuby sejam compilados para Bytecode (e esses Bytecodes serão realmente classes Java válidas), mas até o momento essa é a solução mais elegante para o problema.</p>
<p><b>Nota:</b> não será possível carregar Gems ou bibliotecas instaladas no seu sistema, a não ser que elas sejam descompactadas na pasta &#8220;ruby/lib&#8221;.</p>
<ul>
<p><strong>Mais informações:</strong></p>
<li><a href="http://jruby.org/">Página oficial do JRuby</a></li>
<li><a href="http://kenai.com/projects/jruby/pages/Home">Wiki do JRuby</a></li>
<li><a href="http://www.zkoss.org/">Framework ZK</a></li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Programação Procedural em Java]]></title>
<link>http://mauricioszabo.wordpress.com/2009/11/05/programacao-procedural_em_java/</link>
<pubDate>Thu, 05 Nov 2009 11:58:30 +0000</pubDate>
<dc:creator>Maurício Szabo</dc:creator>
<guid>http://mauricioszabo.wordpress.com/2009/11/05/programacao-procedural_em_java/</guid>
<description><![CDATA[Ok, o título parece estranho, mas é algo que me preocupa: Afinal, POR QUE as pessoas confundem tanto]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Ok, o título parece estranho, mas é algo que me preocupa: Afinal, POR QUE as pessoas confundem tanto desenvolvimento orientado a objeto com procedural? Recentemente eu fiz uma integração do Jasper com Ruby (projeto Jasper on Rails, no meu github) e me vi tendo que usar a API do Jasper. É mais ou menos assim (em JRuby):</p>
<pre>
<pre class="brush: ruby;">
  modelo = &#34;#{DIR}/arquivo.jasper&#34;
  dados = File.read(&#34;#{DIR}/dados.xml&#34;)
  str_reader = java.io.StringReader.new(dados)
  input_source = org.xml.sax.InputSource.new(str_reader)
  documento = JRXmlUtils.parse(input_source)

  params = {
    JRXPathQueryExecuterFactory::PARAMETER_XML_DATA_DOCUMENT =&#62; documento
  }
  fill = JasperFillManager.fill_report(modelo, params)
  pdf = JasperExportManager.export_report_to_pdf(fill)
  return String.from_java_bytes(pdf)
</pre>
</pre>
<p><!--more--></p>
<p>
Ok, tudo bem&#8230; temos classes, temos métodos, mas&#8230; não parece estranho? Esse código é a cara dos códigos que eu já tive que fazer em pascal ou basic, com a diferença que eu acabo escrevendo MUITO mais porque eu preciso me entender com esse monte de Objeto.métodoEstático. A orientação a objeto não foi feita para evitar isso? Não seria mais belo se fosse possível escrever o código assim:</p>
<pre>
<pre class="brush: ruby;">
  modelo = &#34;#{DIR}/#{modelo}.jasper&#34;
  dados = File.read(&#34;#{DIR}/dados.xml&#34;)
  report = JasperReport.new_from_file(modelo)
  report.fill_report_from_string(dados)

  pdf = report.export_report_to_pdf(fill)
  return pdf.to_string
</pre>
</pre>
<p>Simples, um &#8220;new&#8221; que cria um OBJETO, que recebe MÉTODOS&#8230; ao invés de classes funcionando como &#8220;containers de métodos&#8221; que nem o exemplo acima. Claro que no exemplo acima eu simplifiquei o máximo do máximo, mas ainda assim é possível fazer algo mais bonito. A idéia dos &#8220;params&#8221; é boa&#8230; para Ruby, aonde você declara um Hash praticamente sem dificuldade. E para Java, que você precisa IMPORTAR o HashMap, DEFINIR um novo HashMap, criar um monte de &#8220;add&#8221; (ou &#8220;push&#8221;, não lembro a sintaxe de Java) com um monte de constantes que estão dentro de uma classe, para DEPOIS passar isso para uma função&#8230; não seria mais fácil definir uma classe que recebe parâmetros tipo &#8220;setXmlDataDocument&#8221;?</p>
<p>Aonde eu quero chegar? Que mesmo se a linguagem te obrigar a usar um determinado paradigma, se a linguagem for simples, fácil de programar, ainda assim é possível escrever códigos mal escritos. Que a orientação a objeto não significa &#8220;tudo precisa estar numa classe&#8221;, significa que &#8220;uma classe representa um possível objeto, que tem comportamentos específicos&#8221;. Programar orientado a objeto significa pegar um objeto e mudá-lo até ele atender as suas necessidades, e então rodar algum comando que o transforma no que você quer. De preferência se você conseguir pegar algo que as pessoas fazem muito (como no caso do Jasper &#8211; imagino que muitos queiram gerar um PDF) e criar um método que automatiza todas as chamadas (digamos, um JasperReport#to_pdf, mais ou menos como eu fiz no exemplo acima) você finalmente criará um código LIMPO. Não interessa se aquele código que você escreveu só faz chamadas a outros métodos públicos.</p>
<p>E principalmente, mantenha o código conciso. Se você criou um método &#8220;to_pdf&#8221;, não crie outro &#8220;to_xls_file&#8221;. Mantenha as definições semelhantes (mais uma vez, no Jasper, eu tive que enfrentar coisas estranhas &#8211; alguns relatórios você precisa chamar o exportReportToPdf(), e outros você precisava criar um &#8220;Exporter&#8221;, falar que ele vai exportar para um Stream e depois chamar o &#8220;export&#8221; do exporter&#8230;).</p>
<p>Por fim, para quem entende inglês, segue um vídeo extremamente interessante: The Art of Application Development (<a href="http://www.mefeedia.com/watch/24603213" target="_blank">http://www.mefeedia.com/watch/24603213</a>)</p>
<p>Na dúvida, lembrem-se do princípio KISS &#8211; Keep It Simple, Stupid!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Running JRuby with Terracotta]]></title>
<link>http://thinkingbox.wordpress.com/2009/10/27/running_jruby_with_terracotta/</link>
<pubDate>Tue, 27 Oct 2009 19:59:01 +0000</pubDate>
<dc:creator>thinkingbox</dc:creator>
<guid>http://thinkingbox.wordpress.com/2009/10/27/running_jruby_with_terracotta/</guid>
<description><![CDATA[Lately I have been doing some interesting work integrating Terracotta in our application. We use Ter]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Lately I have been doing some interesting work integrating <a title="Terracotta home" href="http://terracotta.org" target="_blank">Terracotta</a> in our application. We use Terracotta in a very limited scenario: as a tool to implement asynchronous DB replication on <a title="PostgreSQL home" href="www.postgresql.org" target="_blank">PostgreSQL</a> (unfortunately the existing tools out there are not suitable for the kind of usage that we do of PostgreSQL &#8211; anyways, I&#8217;ll talk more in details about this in further posts).<br />
At a certain point in time we decided to drive some java code with <a title="JRuby home" href="http://jruby.org" target="_blank">JRuby</a>, in order to process information like log files more efficiently. The java code needed to integrate with Terracotta, so we have had to modify jruby scripts in the following way (eg.: jruby_tc.bat on Windows):</p>
<pre>
<pre style="padding-left:30px;">@echo off
rem ---------------------------------------------------------------------------
rem jruby.bat - Start Script for the JRuby Interpreter
rem
rem for info on environment variables, see internal batch script _jrubyvars.bat

setlocal

<strong>rem Terracotta
set TC_INSTALL_DIR="C:\Program Files\terracotta\terracotta-3.0.1"
set TC_CONFIG_PATH="C:\whatever\tc-config.xml"
call %TC_INSTALL_DIR%\bin\dso-env.bat -q
set JAVA_OPTS=%JAVA_OPTS% %TC_JAVA_OPTS%</strong>

rem Sometimes, when jruby.bat is being invoked from another BAT file,
rem %~dp0 is incorrect and points to the current dir, not to JRuby's bin dir,
rem so we look on the PATH in such cases.
IF EXIST "%~dp0_jrubyvars.bat" (set FULL_PATH=%~dp0) ELSE (set FULL_PATH=%~dp$PATH:0)

call "%FULL_PATH%_jrubyvars.bat" %*

if %JRUBY_BAT_ERROR%==0 "%_STARTJAVA%" %_VM_OPTS% -Xbootclasspath/a:"%JRUBY_CP%" -classpath ^
   "%CP%;%CLASSPATH%" -Djruby.home="%JRUBY_HOME%" -Djruby.lib="%JRUBY_HOME%\lib" ^
   -Djruby.shell="cmd.exe" -Djruby.script=jruby.bat org.jruby.Main %JRUBY_OPTS% %_RUBY_OPTS%
set E=%ERRORLEVEL%

call "%FULL_PATH%_jrubycleanup"

rem 1. exit must be on the same line in order to see local %E% variable!
rem 2. we must use cmd /c in order for the exit code properly returned!
rem    See JRUBY-2094 for more details.
endlocal &#38; cmd /d /c exit /b %E%
</pre>
</pre>
<p>The relevant differences are in bold in the batch file above. I&#8217;ve called the batch jruby_tc.bat in order to differentiate it from usual jruby.bat. As you can see these changes are for Terracotta 3.0.1 but they should work just the same for Terracotta 3.1</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Rails Summit 2009 - Chad Fowler]]></title>
<link>http://andrefaria.com/2009/10/15/rails-summit-2009-chad-fowler/</link>
<pubDate>Fri, 16 Oct 2009 02:37:13 +0000</pubDate>
<dc:creator>andrefaria</dc:creator>
<guid>http://andrefaria.com/2009/10/15/rails-summit-2009-chad-fowler/</guid>
<description><![CDATA[Depois de ter me impressionado com a qualidade do evento Rails Summit 2008 e a força da comunidade R]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Depois de ter me impressionado com a qualidade do <a href="http://andrefaria.com/2008/10/20/participacao-no-rails-summit-latin-america/">evento Rails Summit 2008</a> e a força da comunidade Ruby, não poderia de forma alguma deixar de marcar presença novamente este ano. O evento foi realizado nos dias 13 e 14 de outubro na cidade de São Paulo no auditório Elis Regina do Anhembi, e com uma organização novamente fantástica, contando com excelentes palestrantes, e uma audiência que sem dúvida está acima da média, o evento foi mais uma vez um sucesso total. Parabéns <a href="http://www.akitaonrails.com/">Akita</a> e equipe <a href="http://www.locaweb.com.br">Locaweb</a>!</p>
<p>Nesta série de posts que começa com este, quero registrar os pontos mais importantes e minhas principais impressões sobre a edição 2009 do evento.</p>
<p><a href="http://chadfowler.com">Chad Fowler</a> deu largada com a apresentação do keynote &#8220;<strong>Insurgência Ruby on Rails&#8221;</strong> em que explorou estratégias para insurgências de Ruby on Rails em ambientes pouco amigáveis. Logo no inicio da palestra Chad digiriu-se aos desenvolvedores dizendo &#8220;<em><strong>parem de fazer coisas que vocês sabem que estão erradas</strong></em>&#8220;,  sabemos que todos os dias, muitos de nós desenvolvedores realizamos nosso trabalho de forma burocrática e pouco produtiva, nem sempre utilizamos as melhores práticas e nem sempre temos <strong><a href="http://improveit.com.br/xp/valores/coragem">coragem</a></strong> suficiente para transformar essa realidade.</p>
<div class="wp-caption aligncenter" style="width: 460px"><a href="http://www.flickr.com/photos/danicuki/"><img class=" " title="Chad Fowler por Daniel Cukier" src="http://farm3.static.flickr.com/2607/4008587336_9347f99bcd.jpg" alt="Chad Fowler por Daniel Cukier" width="450" height="300" /></a><p class="wp-caption-text">Chad Fowler por Daniel Cukier</p></div>
<p>Segundo Chad, ao se tentar introduzir desenvolvimento ágil, ruby, rails e novas tecnologias nas organizações geralmente nos deparamos com <strong>monstros guardiões</strong> que tentam proteger suas empresas de <strong>mudanças </strong>a todo o custo, e eles o fazem por causa do fenômeno <a href="http://en.wikipedia.org/wiki/Fear,_uncertainty_and_doubt">FUD </a>(<em>Fear, uncertainty and doubt</em> &#8211; <strong>medo, incerteza e dúvida), </strong>por alguma razão eles tem medo, medo de sair da zona de conforto, <strong>medo de lutar contra a inércia</strong>, medo perder suas posições, medo de errar, e é então que buscam todo tipo de argumento estúpido para tentar evitar algo novo seja feito.</p>
<p>Esse é o caso da velha conversa mole de que rails não escala, isso graças aos problemas que o twitter, um famoso case de rails, enfrentou no passado, &#8220;<em><strong>o twitter não escalava por causa de sua arquitetura</strong></em>&#8221; disse Chad. A lista de desculpas dos tais guardiões não pára por aí, eles dizem que <strong>ruby é lento</strong>, &#8220;mas é claro que é, e quem se importa? O ruby é responsável por em torno de <strong>apenas 6% do tempo de request</strong> de uma aplicação web tradicional&#8221; afirma Chad. Eles perguntarão &#8220;mas dá pra fazer isso? e aquilo?&#8221; e não vão parar até que finalmente encontrem alguma coisas que lhes sirva de desculpa. Mas afinal de contas quem são esses caras? Será que você tem sido um deles?</p>
<p style="text-align:center;">
<div class="wp-caption aligncenter" style="width: 410px"><a href="http://www.flickr.com/photos/gmacorig/"><img class="  " title="Two dragons... (the gate to the end) por Giampaolo Macorig" src="http://farm1.static.flickr.com/46/106472343_689686aa68.jpg" alt="Two dragons... (the gate to the end) por Giampaolo Macorig" width="400" height="366" /></a><p class="wp-caption-text">Two dragons... (the gate to the end) por Giampaolo Macorig</p></div>
<p>Para ajudá-lo na batalha contra os guardiões, Chad recomendou a leitura do artigo &#8220;<a href="http://www.paulgraham.com/avg.html">beating the averages</a>&#8221; de <a href="http://www.paulgraham.com/">Paul Graham</a> e acrescentou procure fazer as coisas de forma gradual, se você tentar fazer uma mudança massiva, provavelmente vai acabar fazendo uma bagunça. Você pode até mesmo começar a usar <a href="http://railroad.rubyforge.org/">rails como uma ferramenta case</a>, é possível fazer algo parecido com o que propõe o <a href="http://www.nakedobjects.org">naked objects</a> com java. Use também  Ruby para criar scripts. Use Ruby para testar java, .net, c++.  Use Ruby para gerar código. Use Ruby como <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html">template engine</a>. Automatize o seu deployment com <a href="http://www.capify.org/index.php/Capistrano">capistrano</a>. Use Ruby para construir protótipos de UI. <strong>Crie metas mensuráveis, meça e apresente resultados</strong>!</p>
<p>Um outro ponto importante é que para introduzir Rails você não precisa necessariamente jogar fora o seu investimento anterior, <a href="http://www.ironruby.net/">IronRuby</a>, <a href="http://jruby.org/">JRuby</a> e etc estão aí para entre outras coisas, te ajudar com isso, mas tome cuidado para não acabar escrevendo código Ruby da mesma forma que você escreve código Java ou C#, entenda que os paradigmas são diferentes e <strong>não tente abrir a casa nova com a chave da velha</strong>.</p>
<p>Chad recomendou ainda a leitura de sua série de artigos &#8220;<a href="http://chadfowler.com/2006/12/27/the-big-rewrite">The Big Rewrite</a>&#8221; e enfatizou <strong>conserve a <a href="http://andrefaria.com/2009/03/18/pense-grande-como-donald-trump/">paixão</a> pelo seu trabalho</strong>.</p>
<p>Assista <a href="http://blip.tv/file/2726795/">a palestra na integra</a> gentilmente gravada e disponibilizada por <a href="http://www.agaelebe.com.br/">Hugo Borges</a>:</p>
<p><!--blip.tv pattern not matched in posts_id=2746679&#38;dest=-1--></p>
<p>Em breve publicarei sobre mais palestras, a<a href="http://feeds.feedburner.com/andrefaria">ssine o feed</a> e acompanhe!</p>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:252px;width:1px;height:1px;">ruby is slow? of course it is but who cares? ruby is reponsible of about 6% of a web request in typical application.</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Java platform gems in Rails]]></title>
<link>http://badurowie.org/2009/10/10/java-platform-gems-in-rails/</link>
<pubDate>Sat, 10 Oct 2009 09:02:44 +0000</pubDate>
<dc:creator>Łukasz</dc:creator>
<guid>http://badurowie.org/2009/10/10/java-platform-gems-in-rails/</guid>
<description><![CDATA[I&#8217;ve recently ecountered a problem with freezing java platform gems in a Rails application I]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;ve recently ecountered a problem with freezing java platform gems in a Rails application I&#8217;m working on. The problem was, that the Rails::GemDependency class would assume that a gem&#8217;s version is the last part of it&#8217;s directory name:</p>
<pre class="brush: ruby;">
      directory_name_parts = File.basename(directory_name).split('-')
      name    = directory_name_parts[0..-2].join('-')
      version = directory_name_parts.last
      result = self.new(name, :version =&#62; version)
</pre>
<p>For java platform gems, directory names often look like e.g. <strong>RedCloth-2.2.2-universal-java</strong>. In this case we would end up with the version variable to be set to &#8216;java&#8217;, and the attempt to create a new object would result in an error. Since I really needed those JRuby compatible gems, I&#8217;ve prepared a small patch and filed a ticket in the Rails project. Both can be found here: <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3356">https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3356</a>. I hope this helps somebody with unpacking the java platform gems into the Rails&#8217; vendor directory.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JRuby bliss]]></title>
<link>http://badurowie.org/2009/10/10/jruby-bliss/</link>
<pubDate>Sat, 10 Oct 2009 08:21:41 +0000</pubDate>
<dc:creator>Łukasz</dc:creator>
<guid>http://badurowie.org/2009/10/10/jruby-bliss/</guid>
<description><![CDATA[I&#8217;ve been fiddling with JRuby for about a month now and I have to say it&#8217;s great. For th]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;ve been fiddling with <a href="http://www.jruby.org">JRuby</a> for about a month now and I have to say it&#8217;s<br />
great. For those of you who don&#8217;t know what it is &#8211; it&#8217;s an implementation of<br />
the Ruby language written in Java. Most people are familiar only with the<br />
Matz&#8217;s implementation in C (MRI = Matz&#8217;s Ruby Interpreter also known as<br />
CRuby). Having Ruby available on top of the JVM is a big leverage. I was<br />
surprised how easy it was to incorporate Java code into Ruby code and vice<br />
versa.</p>
<p>The most work I do is web development with Rails. <a href="http://www.jruby.org">JRuby</a> supports Rails since<br />
version 0.9. Right now it runs all Rails test cases, is <del datetime="2009-10-10T14:37:34+00:00">compatible</del> <a href="http://kenai.com/projects/jruby/pages/Ruby1_9Support">partialy compatible</a> with Ruby<br />
1.9 and improved performance. The existing Rails applications<br />
I&#8217;ve worked on run significantly faster on <a href="http://www.jruby.org">JRuby</a> than on CRuby (JVM rocks).<br />
You also get to compile your Ruby classes to Java classes or use your<br />
favourite Java libraries in you Ruby apps.</p>
<p>The only downside at the moment is the Gem compatibility issues (not all Ruby<br />
code runs on JRuby, however can be adjusted in most cases). <a href="http://www.jruby.org">JRuby</a> doesn&#8217;t<br />
support the use of native extensions which in consequence forces you to swap<br />
some gems for others or to find pure Ruby (which means <a href="http://www.jruby.org">JRuby</a> compatible)<br />
implementations.</p>
<p>The bottom line is, <a href="http://www.jruby.org">JRuby</a> provides you with exciting new possibilities. I&#8217;m<br />
looking forward to see the next releases by the <a href="http://www.jruby.org">JRuby</a> team.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Managing multiple ruby versions and rails versions with rvm]]></title>
<link>http://funonrails.wordpress.com/2009/09/30/managing-multiple-ruby-versions-and-rails-versions-with-rvm/</link>
<pubDate>Wed, 30 Sep 2009 07:32:55 +0000</pubDate>
<dc:creator>sandipransing</dc:creator>
<guid>http://funonrails.wordpress.com/2009/09/30/managing-multiple-ruby-versions-and-rails-versions-with-rvm/</guid>
<description><![CDATA[While working with many projects that uses different ruby versions and rails versions, one big probl]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>While working with many projects that uses different ruby versions and rails versions, one big problem arises that how do we manage all this ?</p>
<p>We know that managing multiple rails versions wont be problem at all.<br />
but what about ruby versions, How one can manage multiple ruby versions. also while upgrading or degrading ruby version, we need to install all gems again including rails.<br />
i know this is a big pain <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /><br />
How we can overcome this headache. meantime there must be some incompatibilities between two different ruby and rails versions.</p>
<p>Yesterday, i did some research and came to know that&#8230;</p>
<p>+ ruby 1.8.7 and rails 2.3.3 got quite stability and effectively. we can use it in next developments.<br />
+ Also, after installing ruby 1.9.1 and dependent gems for my project,<br />
and wondering that there are many incompatibilities while installing new gems with ruby 1.9.1</p>
<p>Some of the gems are mysql, ferret, acts_as_ferret, erubies, etc.</p>
<p>Today, while google, i found rvm gem and that seems very nice to manage multiple ruby versions.</p>
<p>Here are some steps explaining how to use it.</p>
<p># Install rvm gem to manage multiple ruby version<br />
# pre-requisite is that we already have ruby and rubygems installation<br />
<code>1. sudo gem install rvm</code></p>
<p># Install rvm for a particular user<br />
# It will also show how to use gem<br />
<code>2. rvm-install</code></p>
<p>3. Open new shell</p>
<p># Show all ruby, jruby installations<br />
<code>4. rvm list</code></p>
<p># Install ruby<br />
# specify ruby version<br />
<code>5. rvm install RUBY_VERSION_TO_BE_INSTALLED</code><br />
    (rvm install 1.9.1)</p>
<p># Install jruby<br />
# By default it will install jruby-1.3.1<br />
<code>6. rvm install jruby</code></p>
<p># Specify which ruby version to use ?<br />
# Note: Be sure that ruby version is installed<br />
<code>7. rvm use RUBY_VERSION_TO_USE </code><br />
    (rvm use 1.9.1)</p>
<p>#. Default i.e. version before rvm gem installation<br />
<code>8. rvm use default</code></p>
<p>Sounds, cool <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[jruby rails installation on ubuntu interpid]]></title>
<link>http://funonrails.wordpress.com/2009/09/29/jruby-rails-installation-on-ubuntu-interpid/</link>
<pubDate>Tue, 29 Sep 2009 10:22:16 +0000</pubDate>
<dc:creator>sandipransing</dc:creator>
<guid>http://funonrails.wordpress.com/2009/09/29/jruby-rails-installation-on-ubuntu-interpid/</guid>
<description><![CDATA[# install mysql if you dont have already installed sudo apt-get install mysql-server mysql-client li]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p># install mysql if you dont have already installed<br />
sudo apt-get install mysql-server mysql-client libhtml-template-perl mailx dbishell libcompress-zlib-perl mysql-doc-5.0 tinyca</p>
<p># install ant and jdk<br />
sudo apt-get install ant sun-java6-jdk</p>
<p># install jruby<br />
mkdir software<br />
cd software<br />
wget http://dist.codehaus.org/jruby/jruby-bin-1.1.5.tar.gz<br />
tar xvfz jruby-bin-1.1.5.tar.gz<br />
ln -s jruby-1.1.5 jruby<br />
export PATH=$PATH:$HOME/software/jruby/bin</p>
<p># install the version of rails wanted by jruby<br />
jruby -S gem install jruby-openssl<br />
jruby -S gem install rails</p>
<p># list your gems<br />
jruby -S gem list</p>
<p># install the gems needed for db<br />
jruby -S gem install activerecord-jdbc-adapter activerecord-jdbcmysql-adapter</p>
<p># generate some code<br />
cd ~/scripts/ruby<br />
jruby -S rails wherehaveyoubeen -d mysql<br />
cd wherehaveyoubeen<br />
jruby script/generate controller states index</p>
<p># configure access to the database server<br />
vi config/database.yml</p>
<p>#development:<br />
#  adapter: jdbcmysql &#60;- very important!<br />
#  encoding: utf8<br />
#  database: test_development<br />
#  username: root<br />
#  password: database<br />
#  socket: /var/run/mysqld/mysqld.sock</p>
<p># generate the db<br />
jruby -S rake db:create:all<br />
jruby -S rake db:migrate</p>
<p># edit your app<br />
sudo apt-get install emacs ruby-elisp irb1.8 emacs22-el<br />
emacs -bg black -fg wheat app/views/states/index.html.erb</p>
<p># uncomment the secret in app/controllers/application.rb<br />
vi app/controllers/application.rb</p>
<p># run your app<br />
jruby script/server</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[New features in ActiveRecord Oracle enhanced adapter version 1.2.2]]></title>
<link>http://blog.rayapps.com/2009/09/28/new-features-in-activerecord-oracle-enhanced-adapter-version-1-2-2/</link>
<pubDate>Mon, 28 Sep 2009 17:55:34 +0000</pubDate>
<dc:creator>Raimonds Simanovskis</dc:creator>
<guid>http://blog.rayapps.com/2009/09/28/new-features-in-activerecord-oracle-enhanced-adapter-version-1-2-2/</guid>
<description><![CDATA[During the last months many new features have been implemented for ActiveRecord Oracle enhanced adap]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>During the last months many new features have been implemented for ActiveRecord <a href="http://github.com/rsim/oracle-enhanced">Oracle enhanced adapter</a> which are now included in Oracle enhanced adapter version 1.2.2. You can find full list in <a href="http://github.com/rsim/oracle-enhanced/blob/master/History.txt">change history file</a>, here I will tell about the main ones.</p>
<h3>Documentation</h3>
<p>Now Oracle enhanced adapter has improved RDoc documentation for all public methods. So you can go to RDoc documentation of installed gem or go and <a href="http://oracle-enhanced.rubyforge.org/rdoc">view published documentation on-line</a>.</p>
<h3>Schema definition</h3>
<p>There are many new features in schema definition methods that you can use in migration files:</p>
<ul>
<li>When you use <strong>add_index</strong> then ActiveRecord is automatically generating index name using format index_table_name_on_column1_and_column2_&#8230; which previously could cause Oracle errors as Oracle identifiers should be up to 30 characters long. Now default index names are <strong>automatically shortened down to 30 or less characters</strong> (of course you can always use also :name option to specify shortened version by yourself).</li>
<li>Now adapter is <strong>ignoring :limit option for :text and :binary columns</strong> (as in Oracle you cannot specify limit for CLOB and BLOB data types). Previously it could cause errors if you tried to migrate Rails application from e.g. MySQL where :text and :binary columns could have :limit in schema definition.</li>
<li>If you define <strong>:string column with :limit option</strong> then it will define <strong>VARCHAR2 column with size in characters and not in bytes</strong> (this makes difference if you use UTF-8 with language where one character might be stored as several bytes). This is expected behavior from ActiveRecord that you define maximum string size in UTF-8 characters.</li>
<li>Now you can use <strong>add_foreign_key</strong> and <strong>remove_foreign_key</strong> to define foreign key constraints in migrations (see <a href="http://oracle-enhanced.rubyforge.org/rdoc/classes/ActiveRecord/ConnectionAdapters/OracleEnhancedSchemaStatementsExt.html#M000010">RDoc documentation for details</a>). Syntax and some implemenatation for foreign key definition was taken from <a href="http://github.com/matthuhiggins/foreigner">foreigner Rails plugin</a> as well as some ideas taken from <a href="http://github.com/eyestreet/active_record_oracle_extensions">active_record_oracle_extensions plugin</a>.</li>
<li><strong>add_foreign_key</strong> definitions will be also <strong>extracted in schema.rb</strong> by <strong>rake db:schema:dump</strong> task. Therefore they will be also present in test database when you will recreate it from schema.rb file.</li>
<li>Foreign keys are also safe for loading of fixtures (in case you are still using them instead of factories <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). <strong>disable_referential_integrity</strong> method is implemented for Oracle enhanced adapter which is called by ActiveRecord before loading fixtures and which disables all currently active foreign key constraints during loading of fixtures.</li>
<li>You can use <strong>add_synonym</strong> and <strong>remove_synonym</strong> to <a href="http://oracle-enhanced.rubyforge.org/rdoc/classes/ActiveRecord/ConnectionAdapters/OracleEnhancedSchemaStatementsExt.html#M000012">define database synonyms</a> to other tables, views or sequences. add_synonym definitions will also be extracted in schema.rb file.</li>
<li>It is possible to create tables with <a href="http://oracle-enhanced.rubyforge.org/rdoc/classes/ActiveRecord/ConnectionAdapters/OracleEnhancedAdapter.html#M000032">primary key trigger</a>. There will be no difference in terms how you would create new records in such table using ActiveRecord but in case you have also need to do direct INSERTs into the table then it will be easier as you can omit primary key from INSERT statement and primary key trigger will populate it automatically from corresponding sequence.</li>
<li>ActiveRecord <strong>schema dumper is patched</strong> to work correctly when default <strong>table prefixes or suffixes</strong> are used &#8211; they are now removed from schema.rb dump to avoid duplicate prefixes and suffixes when recreating schema from schema.rb.</li>
</ul>
<h3>Legacy schema support</h3>
<p>Some features which can support &#8220;weird&#8221; legacy database schemas:</p>
<ul>
<li>If you are using ActiveRecord with legacy schema which have tables with triggers that populate primary key triggers (and not using default Rails and Oracle enhanced adapter conventions) then you can use <strong>set_sequence_name :autogenerated</strong> in class definition to tell adapter to omit primary key value from INSERTs.</li>
<li>You can use ActiveRecord also with <strong>tables that you can access over database link</strong>. To do that you need to define local synonym to remote table (and also remote sequence if you want to insert records as well) and then use local synonym in set_table_name in class definition. Previously adapter could not get remote table columns, now it will get table columns also over database link.<br />
But still you cannot specify remote table (like &#8220;table_name@db_link&#8221;) directly in set_table_name as table_name will be used as column prefix in generated SQL statements where &#8220;@db_link&#8221; will not be valid syntax.<br />
And when you define local synonyms then please use the new add_synonym feature <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<h3>Connection options</h3>
<ul>
<li><strong>cursor_sharing</strong> option default value is changed from &#8220;similar&#8221; to &#8220;<strong>force</strong>&#8221; &#8211; please read <a href="http://groups.google.com/group/oracle-enhanced/browse_thread/thread/90d1bfbbc02397b5">explanation in discussion group post</a> what it is and why the new default value is recommended choice.</li>
<li>When using <strong>JRuby</strong> and JDBC you can set TNS_ADMIN environment variable to tnsnames.ora directory and then use <strong>TNS database alias</strong> in database.yml file (specify just database: option and remove host: option). This might be useful for more complex TNS connection definitions, e.g. connection to load balanced Oracle RAC.</li>
<li>Adapter will not raise error if it cannot locate <strong>ojdbc14.jar</strong> file. So either put it in $JRUBY_HOME/lib or ensure that it will be loaded by application server. Would love to hear feedback from people who are using this adapter with JRuby to find out if this behaves well now <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<h3>Logging</h3>
<ul>
<li>Now you can get <strong>PL/SQL debugging</strong> information into your ActiveRecord log file. Use <strong>dbms_output.put_line</strong> in your PL/SQL procedures and functions (that are called from ActiveRecord models) and in your ActiveRecord model use <strong>connection.enable_dbms_output</strong> and <strong>connection.disable_dbms_output</strong> around your database calls to get dbms_output logging information into ActiveRecord log file. But please use it just in development environment with debug log level as in production it would add too much overhead for each database call. And this feature also requires that you install ruby-plsql gem.</li>
</ul>
<p>As you see this probably is the largest &#8220;point&#8221; release that I have had <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Thanks also to other contributors which patches were included in this release.</p>
<p>As always you can install Oracle enhanced adapter on any Ruby platform (Ruby 1.8.6 / 1.8.7 or Ruby 1.9.1 or JRuby) with</p>
<pre>
gem install activerecord-oracle_enhanced-adapter
</pre>
<p>If you have any questions please use <a href="http://groups.google.com/group/oracle-enhanced">discussion group</a> or post comments here.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Multiple rubygems versions, GEM_HOME and GEM_PATH ]]></title>
<link>http://formatinternet.wordpress.com/2009/09/28/multiple-rubygems-versions-gem_home-and-gem_path/</link>
<pubDate>Mon, 28 Sep 2009 09:58:37 +0000</pubDate>
<dc:creator>javier ramirez</dc:creator>
<guid>http://formatinternet.wordpress.com/2009/09/28/multiple-rubygems-versions-gem_home-and-gem_path/</guid>
<description><![CDATA[Installing rubygems is failrly easy and it&#8217;s great to have a package manager so you can forget]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Installing <a href="http://rubygems.org/">rubygems</a> is failrly easy and it&#8217;s great to have a package manager so you can forget about manually installing and upgrading the components you use. After installing a gem, you can require it from any ruby script and use it hassle-free. Well, given your ruby interpreter can find it.</p>
<p>When you install rubygems, a lot of default configuration is done behind the scenes. If you must see to believe, you can run</p>
<p><code>gem environment</code></p>
<p>do you believe me now?</p>
<p>Unless you are on windows, you have probably experienced already that gems can get installed in different locations. If using a superuser account, the global configuration will be used, but with a regular account gems install under your home directory. </p>
<p>If you are not careful about how you install your gems, or if you are using rake gems:install from regular accounts, you might end up installing the same version of a gem twice. That&#8217;s not only WET (not DRY, bear with me here) but it eats up your poor HD.</p>
<p>Things can get a lot worse than that. Suppose you are working with both <a href="http://jruby.org/">JRuby</a> and <a href="http://en.wikipedia.org/wiki/Ruby_MRI">Ruby MRI</a>. When you use  rubygems from JRuby, it will try to use a different gem location by default. So, depending on how you are installing gems, you could have up to three different copies of exactly the same version.</p>
<p>And if you are on ubuntu and you upgrade from an old version of rubygems to the latest one &#8212;you will have to if you install Rails 2.3.4; if you are having problems you can <a href="http://formatinternet.wordpress.com/2008/12/02/actualizando-rubygems-a-la-version-131/">read right here</a> how to update it&#8212; you might be surprised that your gems are being installed *again*. The reason is under older versions the default location was &#8220;/var/lib/gems&#8221; and the latest one defaults to &#8220;/usr/lib/ruby/gems&#8221;.</p>
<p>Well, four different copies of <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html">ActiveRecord 2.3.4</a> are three and a half more copies than I wanted, mind you.</p>
<p>So.. how can we stop this gem install frenzy? Easy. Don&#8217;t use the defaults. Each of your installations is using default values, but they can be<a href="http://docs.rubygems.org/read/chapter/11"> easily overridden</a> with command line parameters or much more conveniently with environment variables.</p>
<p>Remember the title of this post? Can you see anything there that would make a good candidate for environment variables? That&#8217;s right, all the rubygems versions honor the GEM_HOME and GEM_PATH variables, so if they are set they will be used.</p>
<p>Depending on your OS, you can set these variables in different places. I&#8217;m on ubuntu and a bit lazy, so I chose the easiest, which is by adding this to my .bashrc file.</p>
<p>export GEM_HOME=/var/lib/gems/1.8<br />
export GEM_PATH=/var/lib/gems/1.8</p>
<p>And now, no matter what I&#8217;m using: Ruby MRI, JRuby, or the latest rubygems, my already installed gems will be used, and the new ones will be put in the same place.</p>
<p>Saving the world is a hard job, but someone has to do it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Initialization Vector Length in MRI Ruby versus JRuby]]></title>
<link>http://blogofheath.com/2009/09/27/initialization-vector-length-in-mri-ruby-versus-jruby/</link>
<pubDate>Sun, 27 Sep 2009 18:22:56 +0000</pubDate>
<dc:creator>heathanderson</dc:creator>
<guid>http://blogofheath.com/2009/09/27/initialization-vector-length-in-mri-ruby-versus-jruby/</guid>
<description><![CDATA[When using OpenSSL encryption in standard Ruby, the length of an initialization vector (IV) can appa]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>When using OpenSSL encryption in standard Ruby, the length of an initialization vector (IV) can apparently be as large as you want it to be as long as it is at least the minimum size. This is odd. This can also cause trouble when switching over to JRuby. JRuby appear to be much pickier about IV length.</p>
<p>This works in MRI but not in JRuby:</p>
<pre class="brush: ruby;">
unencrypted_data = &#34;test&#34;

des = OpenSSL::Cipher::Cipher.new(&#34;des-ede3-cbc&#34;)
des.encrypt
des.key = '0123456789abcdef01234567890'

des.iv = &#34;ed87acdcca419954edccb736f7dc77a74f5ac8dfe3861c3d5f77248e21592131a5423d63ff91f07956ce1aa386f8359931b5&#34; # 100 characters
encrypted_data = des.update(unencrypted_data) + des.final

puts encrypted_data
</pre>
<p>JRuby gives you this very helpful message:<br />
<code>ruby_string_encryption.rb:27:in `encrypt': No message available (OpenSSL::Cipher::CipherError)<br />
from ruby_string_encryption.rb:37</code></p>
<p>Change the IV to 8 characters and everything works fine.</p>
<p><strong>Update 10/14/2009</strong> The code that I originally posted was incorrect. I have updated it. Also I opened a <a href="http://jira.codehaus.org/browse/JRUBY-4012">ticket </a>for this issue. </p>
<p>If you are looking for what size an initialization vector should be check out my post on <a href="http://blogofheath.com/2009/09/25/ruby-string-encryption/">encrypting a string with Ruby</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Deploying Rails app on Glassfish - standalone or shared WAR?]]></title>
<link>http://developerdad.wordpress.com/2009/09/27/deploying-rails-app-on-glassfish-standalone-or-shared-war/</link>
<pubDate>Sat, 26 Sep 2009 22:10:35 +0000</pubDate>
<dc:creator>kto</dc:creator>
<guid>http://developerdad.wordpress.com/2009/09/27/deploying-rails-app-on-glassfish-standalone-or-shared-war/</guid>
<description><![CDATA[We have been working with Glassfish v2 now for a couple of years. We&#8217;re developing mostly usin]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>We have been working with Glassfish v2 now for a couple of years. We&#8217;re developing mostly using Java, but last year we wanted to try implementing one part of our enterprise application with JRuby and Rails. The experiment was good and we decided to continue using Rails on Glassfish.</p>
<p>Our setup was a standalone WAR which included everything needed packaged inside. I wasn&#8217;t personally involved with this application from the beginning and when I started making changes in it I thought that a standalone WAR is the only option. After getting more familiar with Glassfish, I tried the Update Center application and noticed that it&#8217;s possible to install JRuby to Glassfish as a shared component. I started wondering what would be the added benefit of installing JRuby on the application server instead of bundling that in the WAR &#8211; specially as at the moment we only have one Rails application.. Nobody from our team could answer the question and it wasn&#8217;t considered important enough to start investigating it any further.</p>
<p>It was only until two weeks ago when I started wondering about this issue again. It really bothered me since the only thing I could think of as an added benefit of installing JRuby as shared component on the container was that the Rails application WARs become a lot smaller. This was also what <a href="http://twitter.com/arungupta">Arun Gupta</a> hinted to me in <a href="http://twitter.com">Twitter</a> &#8211; see his <a href="http://blog.arungupta.me/2007/12/jruby-on-glassfish-update-center-module-now-updated-with-jruby-1-0-2/">blog entry</a> for more details&#8230;</p>
<p>Not enought I thought&#8230; Also what&#8217;s the point &#8211; imagine you have two Glassfish Clusters in production, both having e.g. three nodes. Using shared JRuby would mean having to maintain versions of JRuby and all the related Gems on six servers in production. And each separately. Using standalone WAR, it&#8217;s maximum two deployments to upgrade JRuby on all six nodes.</p>
<p>Finally last week I got my answer &#8211; and of course it was obvious, one of those when you slap your forehead! Why didn&#8217;t I figure that out myself?! One of the reasons I participated in <a href="http://www.sun.com/offers/details/rails_apps.xml">Sun&#8217;s webinar about deploying Rails apps on Glassfish</a> was the opportunity to ask this one question. The answer I got was:</p>
<blockquote><p>A: When you go in to production , you freeze your gems with app.</p></blockquote>
<p>And of course! I&#8217;m going to set up my own development environment so that Rails app WARs can be made as small as possible, there are also other benefits (like simpler configuring of JRuby options). WARs ending up in the production environment will still be made using the old style standalone configuration.</p>
<p>On the other hand&#8230; I&#8217;m a bit tempted to install Glassfish v3 on my development box just to see the differences in compared to GF v2.1 which we now have in use &#8211; it would also support directory based deployment of Rails apps.</p>
<p>Or maybe I could get directory based Rails deployment work with GF v2.1 as well &#8211; similarly as Java based web application deployment using exploded WARs&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Jruby]]></title>
<link>http://raveendran.wordpress.com/2009/09/10/jruby/</link>
<pubDate>Thu, 10 Sep 2009 11:35:03 +0000</pubDate>
<dc:creator>raveendran</dc:creator>
<guid>http://raveendran.wordpress.com/2009/09/10/jruby/</guid>
<description><![CDATA[Jruby Website &#8211; http://jruby.org/ Code: ravi.rb require &#8220;java&#8221; stringHello= ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Jruby</strong></p>
<p>Website &#8211;<a href="http://jruby.org/" target="_blank"> http://jruby.org/</a></p>
<p>Code:</p>
<p>ravi.rb</p>
<p>require &#8220;java&#8221;</p>
<p>stringHello= &#8220;Raveendran in Ruby&#8221;<br />
stringDate = java.util.Date.new</p>
<p>puts &#8220;#{stringHello.to_s}&#8221;<br />
puts &#8220;Now in Java &#8211;&#62; Date := #{stringDate.to_s}&#8221;</p>
<p>Run the JRuby code:</p>
<p>Go to command promt&#62;jruby ravi.rb</p>
<p>Output:</p>
<p>C:\raveendran\jruby_examples&#62;jruby ravi.rb<br />
Raveendran in Ruby<br />
Now in Java &#8211;&#62; Date := Thu Sep 10 17:03:30 GMT+05:30 2009</p>
<p>C:\raveendran\jruby_examples&#62;</p>
<p>Any issues in installation of JRuby  in windows mnachine then just post a comemnt here.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Instalasi JRuby pada Windows]]></title>
<link>http://tektonayoga.wordpress.com/2009/09/05/instalasi-jruby-pada-windows/</link>
<pubDate>Sat, 05 Sep 2009 18:42:58 +0000</pubDate>
<dc:creator>tektonayoga</dc:creator>
<guid>http://tektonayoga.wordpress.com/2009/09/05/instalasi-jruby-pada-windows/</guid>
<description><![CDATA[Instalasi JRuby pada Windows Download JDK disini. Download distribusi JRuby terbaru disini. Install ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Instalasi JRuby pada Windows</strong></p>
<ol>
<li>Download JDK  <a href="http://java.sun.com/javase/downloads/index.jsp" target="_blank">disini</a>.</li>
<li>Download distribusi JRuby terbaru <a href="http://dist.codehaus.org/jruby/" target="_blank">disini</a>.</li>
<li>Install JDK.</li>
<li>Unzip JRuby pada sembarang directory (dianjurkan &#8220;C:\JRuy).</li>
<li>Ubahlah environtment variable anda seperti dibawah ini:
<ul>
<li>Tambahkan  environtment variable JAVA_HOME , yang berisi path instalasi JDK (Jika lokasi instalasi tidak dirubah maka path untuk 		JAVA_HOME adalah &#8220;C:\Program Files\Java\jdk&#60;VERSI JDK ANDA&#62;&#8221;).</li>
<li>Tambahkan path direcory bin ,yang terdapat pada directory instalasi JRuby, pada environtment variable PATH (Jika JRuby di unzip sesuai dengan yang dianjurkan yakni &#8220;C:\JRuby&#8221; maka directory bin terletak di &#8220;C:\JRuby\bin&#8221;).</li>
</ul>
</li>
<li>Ketik jruby -v untuk memastikan bahwa JRuby telah sukses di install</li>
</ol>
<p><strong>Merubah environtment variable</strong></p>
<ol>
<li>Klik kanan pada My Computer kemudian pilih Properties</li>
<p><img class="alignnone size-full wp-image-5" title="1" src="http://tektonayoga.wordpress.com/files/2009/09/1.jpg" alt="1" width="254" height="224" /></p>
<li>Kemudian pada System Properties pilihlah tab Advanced, kemudian pilih Environtment Variables</li>
<p><img class="alignnone size-full wp-image-6" title="2" src="http://tektonayoga.wordpress.com/files/2009/09/2.jpg" alt="2" width="419" height="479" /></p>
<li>Tambahkan environtment variable JAVA_HOME dan edit environtment variable PATH seperti diatas.</li>
<p><img class="alignnone size-full wp-image-9" title="3" src="http://tektonayoga.wordpress.com/files/2009/09/3.jpg" alt="3" width="384" height="423" /></ol>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Contratempo de aplicação Rails no Mac OS X e Netbeans]]></title>
<link>http://bptecnologia.wordpress.com/2009/08/27/contratempo-de-aplicacao-rails-no-mac-os-x-e-netbeans/</link>
<pubDate>Thu, 27 Aug 2009 17:04:00 +0000</pubDate>
<dc:creator>Benjamin Pinto</dc:creator>
<guid>http://bptecnologia.wordpress.com/2009/08/27/contratempo-de-aplicacao-rails-no-mac-os-x-e-netbeans/</guid>
<description><![CDATA[Na realidade o título está meio ambíguo,  o contratempo não aconteceu nem devido ao rails e muito me]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><div>
<div>
<p>Na realidade o título está meio ambíguo,  o contratempo não aconteceu nem devido ao rails e muito menos devido ao Mac OS X.</p>
<p>Vamos ao fatos:</p>
<p>Na empresa onde trabalho está em funcionamento uma aplicação rails simples, somente com funcionalidade de consulta a um banco MySQL, para atender a um departamento em específico. Como foi necessário desenvolver e entregá-lo num curto espaço de tempo, assim que a codificação foi concluída liberamos a página sem sequer implantala no glassfish (utilizamos JRuby), deixamos a aplicação rodando direto do NetBeans no MackBook de meu colega de trabalho e colocamos as máquinas do departamento para acessa-lo diretamente, via rede interna.</p>
<p>Uma frase que acredito jamais esquecer foi citada por <a href="http://pt.wikipedia.org/wiki/Ricardo_Semler" target="_blank">Ricardo Semler</a> em seu livro “<strong>você está louco!</strong>” que dizia “[...] <em>não existe nada mais permanente que uma solução provisória</em>[...]“. De fato foi isso que ocorreu, dexamos a aplicação rodando dessa forma até então. Passaram-se algumas semanas até que hoje o problema surgiu. Ao que parece a Apple liberou uma atualização para o OS X <span style="text-decoration:line-through;">não sei de que, nem para que</span> e essa atualização além de <span style="text-decoration:line-through;">obviamente</span> atualizar o sistema alterou as configurações do Java para o padrão, alterando a versão definida anteriormente, desconfigurando totalmente o modo de funcionamento da aplicação que dependia da versão da JVM antes selecionada.</p>
<p>Bem nenhum bixo de sete cabeças, pelo menos quando se sabe a origem do problema <span style="text-decoration:line-through;">coisa que demoramos um pouco para perceber</span>.</p>
<p>Fica ai a dica caso você tenha utilizado as mesmas <span style="text-decoration:line-through;">gambiarras</span> metodologias para deixar sua aplicação Rails no ar e se deparou com o mesmo problema, basta redefinir a versão da JVM padrão nas configurações do sistema, de forma simples, como tudo no mac, bastando arrastar e soltar.</p>
<p>Um abraço…</p></div>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Video of my talk "Jruby On Rails" at the Sun Open Communities Forum]]></title>
<link>http://formatinternet.wordpress.com/2009/08/23/video-about-jruby-on-rails-sun-open-communities-forum/</link>
<pubDate>Sun, 23 Aug 2009 17:57:24 +0000</pubDate>
<dc:creator>javier ramirez</dc:creator>
<guid>http://formatinternet.wordpress.com/2009/08/23/video-about-jruby-on-rails-sun-open-communities-forum/</guid>
<description><![CDATA[I just knew the video of my talk about JRuby on Rails at the Sun Open communities Forum is already o]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I just knew the video of my talk about JRuby on Rails at the Sun Open communities Forum is already online. Funny how a google alert let me know this video has been published even before <a href="http://sunopencommunitiesforum.es">the official web page of the event</a> was updated. </p>
<p>The talk is in Spanish and the slides I used are <a href="http://www.slideshare.net/supercoco9/jruby-on-rails-ruby-on-rails-en-la-jvm">available at slideshare</a>.</p>
<p><embed src='http://admin.brightcove.com/destination/player/player.swf' bgcolor='#FFFFFF' flashvars='viewerSecureGatewayURL=https://services.brightcove.com/services/amfgateway&#038;servicesURL=http://services.brightcove.com/services&#038;cdnURL=http://admin.brightcove.com&#038;autoStart=false&#038;initVideoId=34422845001' base='http://admin.brightcove.com' name='bcPlayer' width='480' height='360' allowFullScreen='true' allowScriptAccess='always' seamlesstabbing='false' type='application/x-shockwave-flash' swLiveConnect='true' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' /></p>
<p>If you are a Java developer interested in JRuby and you are going to be in Madrid in September, stay tuned because it&#8217;s very likely I will be speaking again about JRuby in <a href="http://www.simo.ifema.es/es/portal.do">SIMO</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Implantar aplicações Rails em servidores de aplicações Java]]></title>
<link>http://bptecnologia.wordpress.com/2009/08/21/implantar-aplicacoes-rails-em-servidores-de-aplicacoes-java/</link>
<pubDate>Fri, 21 Aug 2009 14:29:05 +0000</pubDate>
<dc:creator>Benjamin Pinto</dc:creator>
<guid>http://bptecnologia.wordpress.com/2009/08/21/implantar-aplicacoes-rails-em-servidores-de-aplicacoes-java/</guid>
<description><![CDATA[Como o título sugere, as linhas abaixo, devidamente CTRL+C/CTRL+V baseadas no tutorial oficial do Ne]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Como o título sugere, as linhas abaixo, devidamente <span style="text-decoration:line-through;">CTRL+C/CTRL+V</span> baseadas no tutorial oficial do <a title="Netbeans" href="http://www.netbeans.org/kb/60/ruby/setting-up_pt_BR.html#glassfish" target="_blank">Netbeans</a>, mostram como implantar sua aplicação Rails num servidor de aplicações Java. Lógicamente você deverá usar o <a title="JRuby" href="http://jruby.org/" target="_blank">JRuby</a> para isso.</p>
<p>O tutorial usa como servidor o Glassfish, porém os procedimentos são os mesmos para qualquer servidor que aceite um projeto na extensão <em>.war</em>.</p>
<p>Aí vai o texto na íntegra:</p>
<p>Por padrão, as aplicações JRuby são executadas no WEBrick. Se você quiser implantar uma aplicação JRuby no servidor da aplicação GlassFish, poderá empacotar a aplicação e suas dependências em um arquivo WAR (web archive). Em seguida, você pode tornar o arquivo WAR disponível para o servidor da aplicação, conforme mostrado nas etapas a seguir.</p>
<ol>
<li>A aplicação implantada usará o banco de dados de produção. Abra o arquivo <tt>database.yml</tt> para garantir que a configuração de produção esteja definida corretamente.</li>
<li>Ao criar a aplicação JRuby, você recebe a opção de adicionar destinos Rake para oferecer suporte ao deployment do servidor da aplicação, conforme mostrado na figura a seguir. Se você pretende implantar no GlassFish, deve marcar esta caixa de verificação.<img src="http://www.netbeans.org/images/articles/60/ruby/setting-up/waroption.png" alt="Opção para fornecer destinos Rake WAR" width="331" height="66" />Se você tiver um projeto JRuby existente que não ofereça este destino Rake, conclua as etapas a seguir para adicionar o plug-in Goldspike ao projeto. Este plug-in adiciona tarefas de Rake que permitem que você crie arquivos WAR.
<ol type="a">
<li>Na janela Projetos, clique com o botão direito do mouse no nó  e escolha Gerar código no menu pop-up.</li>
<li>Na caixa de diálogo Plug-ins Rails, clique na aba Novos plug-ins.</li>
<li>Caso você não veja uma entrada para Goldspike, conclua as etapas a seguir para registrar o repositório que fornece o plug-in Goldspike.
<ol>
<li>Clique na aba Cabeçalhos.</li>
<li>Clique em Adicionar URL.</li>
<li>Na caixa de diálogo Adicionar URL do repositório, digite <tt>http://jruby-extras.rubyforge.org/svn/trunk/rails-integration/plugins</tt> e clique em OK.</li>
<li>Depois que o repositório for adicionado, clique em Fechar.</li>
<li>Clique na aba Novos plug-ins. Agora você deve ver uma entrada para o Goldspike.</li>
</ol>
</li>
<li>Selecione a entrada para Goldspike e clique em Instalar.</li>
<li>Clique em OK para iniciar a instalação.</li>
<li>Feche as caixas de diálogo Instalação e Plug-ins Rails.</li>
<li>Clique com o botão direito do mouse no nó do projeto e escolha Executar tarefa Rake &#62; Atualizar lista do menu pop-up.</li>
</ol>
</li>
<li>Para empacotar a sua aplicação em um arquivo WAR, clique com o botão direito do mouse no nó do projeto e escolha Executar tarefa Rake &#62; War &#62; Independente &#62; Criar.O IDE cria o arquivo WAR e o coloca na pasta superior do projeto.</li>
<li>Se você estiver usando o adaptador JDBC, coloque uma cópia do driver JDBC do servidor do banco de dados em <em>glassfish-install-dir</em><tt>/lib</tt> e inicie (ou reinicie) o servidor GlassFish.No momento desta escrita, você deve usar o adaptador JDBC a menos que esteja se conectando a um banco de dados MySQL.</li>
<li>Coloque uma cópia do arquivo WAR recém-criado na pasta autodeploy do GlassFish.  Por exemplo, copie <em>pasta de projetos</em><tt>/MyRubyApp/MyRubyApp.war</tt> para <em>glassfish-install-dir</em><tt>/domains/domain1/autodeploy</tt>.</li>
<li>Em um navegador, vá para a URL da aplicação, por exemplo,                 <tt>http://localhost:8080/MyRubyApp</tt>.</li>
</ol>
<p>Bem é isso pessoal, espero que seja útil&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Testing The Waters Of Jruby &amp; JDBC]]></title>
<link>http://tompurl.com/2009/08/21/testing-the-waters-of-jruby-jdbc/</link>
<pubDate>Fri, 21 Aug 2009 13:09:17 +0000</pubDate>
<dc:creator>tpurl</dc:creator>
<guid>http://tompurl.com/2009/08/21/testing-the-waters-of-jruby-jdbc/</guid>
<description><![CDATA[I was recently tasked with writing a command-line script in Jruby that performed simple CRUD operati]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I was recently tasked with writing a command-line script in Jruby that performed simple CRUD operations against a simple database table.  I&#8217;ve written tons of scripts in the past that manipulated tables, but I had never done so using Jruby.  I therefore decided to first write a &#8220;bare-minimum&#8221; test script that would help me dip my toes in this unfamiliar water.</p>
<p>I wanted to write my test script against a database manager that ran on my laptop, but I didn&#8217;t want to go through the hassle of installing and configuring Oracle or MySql.  Also, I soon learned that a lot of Ruby database drivers don&#8217;t work with Jruby, so I needed a small, simple database that had a good JDBC driver.  I ended up installing and configuring <a title="Apache Derby" href="http://db.apache.org/derby">Apache Derby</a>, and it worked out very well for me.</p>
<p>So anyways, here&#8217;s the script (jdbctest.rb):</p>
<pre> require 'java'
 require './derbyclient.jar'
 require './derbytools.jar'

 # This example assumes that you have the free DerbyDB software installed on
 # your machine.  It also assumes that you are running it in "server" mode by
 # executing the startNetworkServer.bat script.

 # This is what I'm using instead of Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance()
 import 'org.apache.derby.jdbc.ClientDriver'

 connString = "jdbc:derby://localhost:1527/MyDbTest"
 conn = Java::JavaSql::DriverManager.getConnection(connString)

 stmt = conn.createStatement

 rs = stmt.executeQuery("select * from derbyDb")

 while (rs.next) do
     puts "#{rs.getString("NUM")} -- #{rs.getString("ADDR")}"
 end

 rs.close
 stmt.close
 conn.close()</pre>
<p>I then placed the <strong>jdbctest.rb</strong> script in a folder with the <strong>derbyclient.jar</strong> and <strong>derbytools.jar</strong> file, and then executed the script like this:</p>
<pre> c:\Dev\jruby\somefolder&#62;jruby .\jdbctest.rb
 180 -- Grand Ave.
 1910 -- Union St.</pre>
<p>To make this script work, you need to do the following:</p>
<ol>
<li>Install Derby using this tutorial:  <a title="Step 1 - Install Software" href="http://db.apache.org/derby/papers/DerbyTut/install_software.html">Step 1 &#8211; Install Software</a>
<ul>
<li>This is a very simple task that took me all of 6 minutes after downloading the software.</li>
</ul>
</li>
<li>Create the <strong>MyDbTest</strong> database and the <strong>derbyDB</strong> table using this tutorial: <a title="Step 2 - ij Basics" href="http://db.apache.org/derby/papers/DerbyTut/ij_intro.html">Step 2 &#8211; ij Basics</a>
<ul>
<li>You should also populate this table using the SQL located under the <strong>Execute SQL Statements</strong> section.</li>
</ul>
</li>
<li>Once you&#8217;ve created and queried your table using <code>ij</code>, start your Derby server using this tutorial:  <a title="Step 4 - Derby Network Server" href="http://db.apache.org/derby/papers/DerbyTut/ns_intro.html">Step 4 &#8211; Derby Network Server</a>
<ul>
<li>You should validate the server using <code>ij</code>.  Please see the <strong>Test network server connection with ij</strong> section in the <strong>Step 4</strong> tutorial for help.</li>
</ul>
</li>
</ol>
<p>Please note that this might seem like a lot of work, but it&#8217;s really very simple, especially when you compare it installing and configuring most relational database managers.  It took me about 20 minutes from A to Z, and I had no prior experience with Derby.</p>
<p>That&#8217;s it!  I hope that this tutorial helps a few other people who want to get started with Jruby and JDBC.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using Ruby Java Bindings on Dreamhost and Fill PDF Form with iText]]></title>
<link>http://pdfhacks.wordpress.com/2009/08/18/using-ruby-java-bindings-on-dreamhost-and-fill-pdf-form-with-itext/</link>
<pubDate>Mon, 17 Aug 2009 18:44:29 +0000</pubDate>
<dc:creator>rubypdf</dc:creator>
<guid>http://pdfhacks.wordpress.com/2009/08/18/using-ruby-java-bindings-on-dreamhost-and-fill-pdf-form-with-itext/</guid>
<description><![CDATA[I am familiar with iText , but not familiar with Ruby, I know Dreamhost supports Ruby on Rails(ROR),]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I am familiar with iText , but not familiar with Ruby, I know <a href="http://blog.rubypdf.com/2008/06/13/five-dreamhost-invitations/">Dreamhost</a> supports <strong>Ruby on Rails</strong>(<strong>ROR</strong>), but never have a chance to run a real application, though I have a <a href="http://blog.rubypdf.com/2008/06/13/five-dreamhost-invitations/">Dreamhost</a> space.</p>
<p>Getting rjb, also known as &#8220;Ruby Java Bindings&#8217; to work in a Dreamhost account can be somewhat problematic. Fortunately, it is also fairly straightforward. You just have to install all the dependencies in the user directory.</p>
<p>In my case, I was setting up a Rails Application that used the iText Java library to <strong>fill in PDF documents</strong> for user download. Of course, the server environment was not using Sun Java and the Java headers were not present, so <span style="font-family:Courier New;">gem install rjb</span> failed.  Joy.</p>
<p>The first course of action was to do a local install of Java.</p>
<p>Download <span style="font-family:Courier New;">jdk-6u7-linux-x64.bin</span> and <span style="font-family:Courier New;">jre-6u7-linux-x64.bin</span> from the Sun Java site. Then create an <span style="font-family:Courier New;">~/opt</span> directory and extract the JRE and JDK (you will need to <span style="font-family:Courier New;">chmod u+x</span> both files then call them from the command line).  Move the resulting folders to <span style="font-family:Courier New;">~/opt</span> .   I renamed the folders to<em> jdk</em> and <em>jre</em> for simplicity.</p>
<p>Now you ensure that user gems are enabled in cPanel.  Then add the following 3 lines to <span style="font-family:Courier New;">~/.bash_profile</span></p>
<p><span style="font-family:Courier New;">export JAVA_HOME=/home/username/opt/jdk</span><br />
<span style="font-family:Courier New;">export GEM_PATH=/home/username/ruby/gems</span><br />
<span style="font-family:Courier New;">export GEM_HOME=/home/username/ruby/gems</span></p>
<p>Run <span style="font-family:Courier New;">source ~/.bash_profile</span> to load the paths.</p>
<p>Now you can run <span style="font-family:Courier New;">gem install rjb</span> without any problems. You will likely have to re-install Rails and other gems because we will be telling our Rails app to load gems from the user directory. Just use the regular <span style="font-family:Courier New;">gem install <span style="font-family:Arial;">syntax.</span></span></p>
<p>Add the following 2 lines to your config/environment.rb at the top</p>
<p><span style="font-family:Courier New;">ENV['GEM_PATH']=&#8217;/home/username/ruby/gems&#8217;</span><br />
<span style="font-family:Courier New;">ENV['JAVA_HOME']=&#8217;/home/username/opt/jdk&#8217;</span></p>
<p>That&#8217;s pretty much it.</p>
<p>I will concede that these probably aren&#8217;t the best instructions, but this is the real meat of the solution. If you keep getting &#8220;no such file to load&#8221; errors, you will need to extract the gems to the vendor/plugins directory. <span style="font-family:Courier New;">cd RAILS_ROOT/vendor/plugins</span> and <span style="font-family:Courier New;">gem unpack gem_name</span> for each problematic gem.  I believe this is an issue with Passenger.</p>
<p>Please correct me if I am wrong about any of this, it was a very long day!</p>
<p>source: <a href="http://blog.patrick-morgan.net/2008/10/using-ruby-java-bindings-on-dreamhost.html">http://blog.patrick-morgan.net/2008/10/using-ruby-java-bindings-on-dreamhost.html</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JRuby, Rails, JBoss, and Jfrustration - Fixing Warble 0.9.4's Standard Includes]]></title>
<link>http://coffeesgone.wordpress.com/2009/08/16/jruby-rails-jboss-and-jfrustration-fixing-warble-0-9-4s-standard-includes/</link>
<pubDate>Sun, 16 Aug 2009 21:05:58 +0000</pubDate>
<dc:creator>Sam Baskinger</dc:creator>
<guid>http://coffeesgone.wordpress.com/2009/08/16/jruby-rails-jboss-and-jfrustration-fixing-warble-0-9-4s-standard-includes/</guid>
<description><![CDATA[Work has been busy. Scratch that work has been absolutely insane and confusing and at times, baffeli]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Work has been busy. Scratch that work has been <a href="http://www.scala-lang.org/">absolutely </a><a href="http://hadoop.apache.org/">insane</a> and <a href="http://www.cascading.org/">confusing</a> and at times, <a href="http://www.scala-lang.org/docu/files/api/scala/util/parsing/combinator$package.html">baffeling</a>, but I have to say that I wouldn&#8217;t trade the experience for the world! On the bright side, I&#8217;ve been distracted during what were the two worst weeks for the <a href="http://www.brewers.com/">Brewer&#8217;s</a> season (right now they are beating-up on <a href="http://mlb.mlb.com/mlb/gameday/index.jsp?gid=2009_08_16_houmlb_milmlb_1&#38;mode=gameday">Houston</a>). Now that I have some time to myself I have had dinner w/ the Mrs., read some of the <a href="http://www.amazon.com/Bourne-Identity-Trilogy-Book/dp/0553260111">Bourne Identity</a>, and have gotten back to porting my <a href="http://rubyonrails.org/">Ruby On Rails </a>Knowledge Base application to <a href="http://jruby.codehaus.org/">JRuby </a>on Rails on <a href="http://www.jboss.org/">JBoss</a>. The past few sessions I&#8217;ve spent with the technology have been plagued with the error message:</p>
<blockquote><p><code>2009-08-16 00:27:28,101 ERROR [STDERR] (main) Warning: JRuby home "/home/sam/usr/jboss-5.1.0.GA/server/default/deploy/railskb.war/WEB-INF/lib/jruby-complete-1.3.0RC1.jar/META-INF/jruby.home" does not exist, using /tmp </code></p>
<p><code>2009-08-16 00:27:28,507 ERROR [STDERR] (main) Rails requires RubyGems &#62;= . Please install RubyGems and try again: http://rubygems.rubyforge.org </code></p>
<p><code>2009-08-16 00:27:28,512 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/railskb]] (main) unable to create shared application instance org.jruby.rack.RackInitializationException: exit </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/tmp/3j001-au64oi-fyfc3ruh-1-fyfc4xzj-9p/railskb.war/WEB-INF/config/boot.rb:38:in `run' </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/deploy/railskb.war/WEB-INF/lib/jruby-rack-0.9.4.jar/jruby/rack/rails_boot.rb:20:in `run' </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/tmp/3j001-au64oi-fyfc3ruh-1-fyfc4xzj-9p/railskb.war/WEB-INF/config/boot.rb:11:in `boot!' </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/tmp/3j001-au64oi-fyfc3ruh-1-fyfc4xzj-9p/railskb.war/WEB-INF/config/boot.rb:109 </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/tmp/3j001-au64oi-fyfc3ruh-1-fyfc4xzj-9p/railskb.war/WEB-INF/config/boot.rb:20:in `require' </code></p>
<p><code> from /home/sam/usr/jboss-5.1.0.GA/server/default/tmp/3j001-au64oi-fyfc3ruh-1-fyfc4xzj-9p/railskb.war/WEB-INF/config/environment.rb:20</code></p></blockquote>
<p style="text-align:left;">Notice the odd line &#8220;Rails requires RubyGems &#62;= .&#8221;. Eh? I did a log of digging in google and found about 4 sets of forum posts that identify this problem and correlate it with an upgrade to <a href="http://kenai.com/projects/jruby/pages/JRubyRack">Rack </a>0.9.4 from 0.9.3. I also noticed that Warbler had included in it a copy of <code>jruby-complete-1.3.0RC1.jar</code> and <code>jruby-rack-0.9.4.jar</code> when the version I would like it to use is jruby 1.3.1.</p>
<p style="text-align:left;">After a little failed convincing and JBoss continually showing that while it had included in it jruby 1.3.1 that it was choosing to use, and fail to find the ruby gems, on the 1.3.0RC1 jruby jar mentioned in the log above.</p>
<p style="text-align:left;">Finally, I bit the bullet and decided to punt on Warbler&#8217;s automagically included jars and manually include. To do this I:</p>
<ol>
<li>created <code>lib/java </code>in my rails application directory.</li>
<li>copied into it <code>jruby-complete-1.3.1.jar</code></li>
<li>copied into it <code>jruby-rack-0.9.jar</code></li>
<li>add the line <code>config.java_libs = FileList["lib/java/*.jar"]</code> to  <code>conf/warble.rb</code></li>
</ol>
<p>Loading this into JBoss the application loads! When I access it, it explodes in another fashion, but that&#8217;s fine! I&#8217;m still learning and I&#8217;m past my deployment problems for now!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Configurando ambiente JRuby on Rails + SQLite3 no Windows]]></title>
<link>http://cabritin.wordpress.com/2009/08/13/configurando-ambiente-jruby-on-rails-sqlite3-no-windows/</link>
<pubDate>Thu, 13 Aug 2009 04:24:00 +0000</pubDate>
<dc:creator>tnaires</dc:creator>
<guid>http://cabritin.wordpress.com/2009/08/13/configurando-ambiente-jruby-on-rails-sqlite3-no-windows/</guid>
<description><![CDATA[JRuby é uma implementação da linguagem Ruby escrita 100% em Java que oferece total suporte a Ruby on]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>JRuby é uma implementação da linguagem Ruby escrita 100% em Java que oferece total suporte a Ruby on Rails. O objetivo deste tutorial é configurar um ambiente de desenvolvimento Ruby on Rails no Windows utilizando JRuby e o banco de dados SQLite3. Apesar de ter sido escrito especificamente para Windows, ele pode ser facilmente adaptado para outras plataformas.</p>
<p>No momento da publicação deste tutorial as versões das tecnologias envolvidas eram:</p>
<ul>
<li>Java &#8211; JDK 6 update 14</li>
<li>JRuby &#8211; 1.3.1</li>
<li>Ruby on Rails &#8211; 2.3.3</li>
<li>SQLite3 &#8211; 3.6.17</li>
</ul>
<p>Vamos lá:</p>
<p><strong>Passo 1</strong> &#8211; baixe o JDK diretamente do site da <a title="Sun - downloads" href="http://java.sun.com/javase/downloads/index.jsp" target="_blank">Sun</a> e instale-o conforme recomendado, criando a variável de ambiente JAVA_HOME que aponta para o diretório de instalação e adicionando o caminho %JAVA_HOME%\bin ao PATH.</p>
<p><strong>Passo 2</strong> &#8211; baixe o <a title="JRuby" href="http://jruby.codehaus.org/" target="_blank">JRuby</a> clicando no link Download e selecionando a versão mais atual. Descompacte o arquivo em um local de sua preferência. Crie uma variável de ambiente JRUBY_HOME que aponta para esse local e adicione o caminho %JRUBY_HOME%\bin ao PATH.</p>
<p><strong>Passo 3</strong> &#8211; Entre no site do <a title="SQLite3" href="http://sqlite.org/" target="_blank">SQLite3</a> e clique no link Download. Na seção &#8220;Precompiled Binaries for Windows&#8221; baixe os arquivos <strong>sqlite-&#60;VERSÃO&#62;.zip</strong> e <strong>sqlitedll-&#60;VERSÃO&#62;.zip</strong> (conforme dito anteriormente, a versão contemporânea a este tutorial é a 3.6.17). Crie um diretório no local de sua preferência denominado sqlite3. Descompacte os arquivos .zip baixados dentro desse diretório e configure a variável PATH para apontar para ele.</p>
<p><strong>Passo 4</strong> &#8211; Vamos testar o que instalamos até agora. Abra um prompt de comando e digite:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -v</code></p>
<p>A versão do JRuby instalada no seu computador deve aparecer na tela. Digite agora a linha:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">sqlite3</code></p>
<p>O SQLite3 será executado e ficará aguardando a entrada de comandos de administração. Digite &#8220;.exit&#8221; sem as aspas para sair do SQLite3.</p>
<p><strong>Passo 5</strong> &#8211; Vamos agora instalar o Rails. Abra o prompt de comando, digite a linha:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -S gem install rails</code></p>
<p>e aguarde até o final da instalação. Quando ela terminar, digite:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -S rails -v</code></p>
<p>para visualizar a versão do Rails instalada.</p>
<p><strong>OBS:</strong> o parâmetro -S força o JRuby a procurar o script dentro da pasta &#8220;bin&#8221; ou na variável de sistema PATH.</p>
<p><strong>Passo 6</strong> &#8211; Precisamos instalar também o driver do SQLite3 para o JRuby. Isso pode ser feito digitando a seguinte linha no prompt de comando e pressionando ENTER:</p>
<p><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -S gem install activerecord-jdbcsqlite3-adapter</code></p>
<p>Lembrando de aplicar as configurações de proxy conforme visto anteriormente, caso necessário.</p>
<p><strong>Passo 7</strong> &#8211; Finalmente, criaremos uma aplicação de exemplo para testarmos o ambiente. Navegue pelo prompt de comando até o diretório onde você mantém suas aplicações e digite:</p>
<p><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -S rails teste</code></p>
<p>Edite o arquivo &#8220;config\database.yml&#8221; com a ajuda de um editor de textos. Na configuração do ambiente de desenvolvimento, altere o valor da propriedade &#8220;adapter&#8221; para &#8220;jdbcsqlite3&#8243;.</p>
<p>Entre no diretório &#8220;teste&#8221; e digite a seguinte linha para criar um cadastro de pessoas:</p>
<p><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby script/generate scaffold Person name:string phone:string</code></p>
<p>Crie o banco de dados:</p>
<p><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">rake db:migrate</code></p>
<p>Inicie o servidor:</p>
<p><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby script/server</code></p>
<p>E acesse o endereço &#8220;http://localhost:3000/people&#8221;. Se tudo deu certo, você verá a página que mostra as pessoas cadastradas no sistema.</p>
<p><strong>IMPORTANTE:</strong> se a rede onde está seu computador possui configuração de proxy, é preciso passar essa configuração através do parâmetro -p do comando gem usando a seguinte sintaxe:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">-p http://usuario:senha@servidorproxy:porta</code></p>
<p>Isso deve ser feito para todos os comandos de instalação de gems que foram vistos nesse tutorial. Use o seguinte exemplo como referência:</p>
<p style="text-align:left;"><code style="font-size:11pt;color:#00ff00;background-color:black;padding:5px;">jruby -S gem install rails -p http://tarso:123@meu.proxy.com.br:4321</code></p>
<p>Quaisquer dúvidas e/ou correções, favor postar nos comentários. Até mais!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to run JRuby on Rails on Google's App Engine]]></title>
<link>http://leonardom.wordpress.com/2009/08/06/how-to-run-jruby-on-rails-on-googles-app-engine/</link>
<pubDate>Thu, 06 Aug 2009 12:26:25 +0000</pubDate>
<dc:creator>Leonardo</dc:creator>
<guid>http://leonardom.wordpress.com/2009/08/06/how-to-run-jruby-on-rails-on-googles-app-engine/</guid>
<description><![CDATA[Are you wondering how to install your JRuby on Rails application on Google&#8217;s App Engine? If so]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Are you wondering how to install your JRuby on Rails application on Google&#8217;s App Engine?</p>
<p>If so, go to this <a href="http://rails-primer.appspot.com/">cookbook.</a></p>
<p>I have not tried yet, but I&#8217;ll try soon.</p>
<p>See you! Leo</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
