SlideShare ist ein Scribd-Unternehmen logo
1 von 65
Downloaden Sie, um offline zu lesen
JRuby on Rails
Ruby on Rails sobre la JVM


                                                                                    javier ramírez


http://aspgems.com                                                http://spainrb.org/javier-ramirez

obra publicada por javier ramirez como ‘Atribución-No Comercial-Licenciar Igual 2.5’ de Creative Commons
james duncan davidson
james duncan davidson
Servlet API, Tomcat, Ant, Java API for XML Processing
james duncan davidson
Servlet API, Tomcat, Ant, Java API for XML Processing

Rails is the most well thought-out web development
framework I’ve ever used. And that’s in a decade
of doing web applications for a living.
I’ve built my own frameworks, helped develop the
Servlet API, and have created more than a few
web servers from scratch.
Nobody has done it like this before.
qué


Ruby, el lenguaje
Rails, el framework
JRuby, la plataforma
self

       http://aspgems.com

       http://formatinternet.com
       http://javier.github.com
       http://spainrb.org/javier-ramirez

       jramirez@aspgems.com


       http://twitter.com/supercoco9
tolerancia al dolor
tolerancia al dolor
I've seen things you people wouldn't believe. Attack ships on fire
off the shoulder of Orion. I watched C-beams glitter in the dark...
tolerancia al dolor
I've seen things you people wouldn't believe. Attack ships on fire
off the shoulder of Orion. I watched C-beams glitter in the dark...

He perdido horas en altavista.com buscando cómo
escribir Blobs en DB2 con JDBC
tolerancia al dolor
I've seen things you people wouldn't believe. Attack ships on fire
off the shoulder of Orion. I watched C-beams glitter in the dark...

He perdido horas en altavista.com buscando cómo
escribir Blobs en DB2 con JDBC

JDK 1.0 JAVA 2 RMI/CORBA JNI LDAP JNDI SAX
DOM STAX EJB1 (sin interfaz local) EJB2 Jlex SOAP
JSP XSLT Freemarker
tolerancia al dolor
I've seen things you people wouldn't believe. Attack ships on fire
off the shoulder of Orion. I watched C-beams glitter in the dark...

He perdido horas en altavista.com buscando cómo
escribir Blobs en DB2 con JDBC

JDK 1.0 JAVA 2 RMI/CORBA JNI LDAP JNDI SAX
DOM STAX EJB1 (sin interfaz local) EJB2 Jlex SOAP
JSP XSLT Freemarker

Bancos, Administración Pública, Farmaceúticas, SGAE...
http://ruby-lang.org
ruby

Creado por
Yukihiro Matsumoto
aka “Matz”


Dinámico, Orientado a Objetos y Open Source

Primera versión de desarrollo en 1993

Primera versión oficial en 1995
                          foto con licencia creative commons por Javier Vidal Postigo
                          fuente: flickr
así que desde 1995...



¿Y cómo es que no
supe nada de ruby
hasta mucho más
tarde?
1995   2002
¿por qué un nuevo lenguaje?

Hipótesis de Sapir-Whorf: todos los
pensamientos teóricos están basados en
el lenguaje y están condicionados por
él




                                fuente: wikipedia
¿por qué un nuevo lenguaje?

Hipótesis de Sapir-Whorf: todos los
pensamientos teóricos están basados en
el lenguaje y están condicionados por
él

Los diferentes lenguajes de
programación, condicionan la forma en
que los programadores desarrollan sus
soluciones
                    fuente: the power and philosophy of ruby
                    http://www.rubyist.net/~matz/slides/oscon2003/
¿por qué ruby?
Diseñado para ser divertido, creativo, y
reducir el estrés del programador.
Centrado en la resolución de problemas




                        fuente: the power and philosophy of ruby
                        http://www.rubyist.net/~matz/slides/oscon2003/
¿por qué ruby?
Diseñado para ser divertido, creativo, y
reducir el estrés del programador.
Centrado en la resolución de problemas
Las personas son buenas      Las personas no son
en                           buenas en
•Creatividad                 •hacer copias
•Imaginación                 •trabajos rutinarios
•Resolución de problemas     •cálculos, etc…

                           fuente: the power and philosophy of ruby
                           http://www.rubyist.net/~matz/slides/oscon2003/
principios de diseño

principio de la mínima sorpresa

principio de la brevedad (succinctness)

principio de la interfaz humana

enviar mensajes “ocultos” (syntactic sugar)

                         fuente: the power and philosophy of ruby
                         http://www.rubyist.net/~matz/slides/oscon2003/
convenciones en ruby
  ClassNames
  method_names and variable_names
  methods_asking_a_question?
  slightly_dangerous_methods!
  @instance_variables
  $global_variables
  SOME_CONSTANTS or OtherConstants



            fuente: 10 Things Every Java Programmer Should Know About Ruby
            http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
orientación “pura” a objetos
Alan Kay

Actually I made up the term "object-oriented", and I can
tell you I did not have C++ in mind
orientación “pura” a objetos
Alan Kay (2003)

Actually I made up the term "object-oriented", and I can
tell you I did not have C++ in mind

OOP to me means only messaging, local retention and
protection and hiding of state-process, and extreme late-
binding of all things. It can be done in Smalltalk and in
LISP. There are possibly other systems in which this is
possible, but I'm not aware of them


                fuente: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en
todo es un objeto
   las clases son objetos => Array.new

   ejemplo de factoría en ruby

     def create_from_factory(factory)
         factory.new
     end

       obj = create_from_factory(Array)



                fuente: 10 Things Every Java Programmer Should Know About Ruby
                http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
nil es un objeto
nil.nil?
=> true

nil.methods.grep /?/

=> ["instance_variable_defined?",
"equal?", "respond_to?", "eql?",
"frozen?", "instance_of?", "kind_of?",
"tainted?", "nil?", "is_a?"]
todo es un objeto.sin primitivas
 0.zero?    # => true
 true.class #=> TrueClass
 1.zero?    # => false
 1.abs      # => 1
 -1.abs     # => 1
 1.methods # => métodos del objeto 1
 2.+(3)     # => 5 (igual que 2+3)
 10.class   # => Fixnum
 (10**100).class # => Bignum
 Bignum.class # => Class
 (1..20).class #=> Range

               fuente: 10 Things Every Java Programmer Should Know About Ruby
               http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
dinámico
Reflection muy simple
Clases Abiertas
Objetos Singleton
Hooks integrados
Evaluación dinámica
Mensajes dinámicos
ObjectSpace



                  fuente: 10 Things Every Java Programmer Should Know About Ruby
                  http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
dinámico. ejemplos
def create(klass, value)             class MyClass
                                       def MyClass.method_added(name)
  klass.new(value)
                                         puts "Adding Method #{name}"
end                                    end
create(Greeting, "Hello")
                                       def new_method
                                         # Yada yada yada
class Integer                          end
  def even?                          end
    (self % 2) == 0
  end
end
3.even?
=> false




                      fuente: 10 Things Every Java Programmer Should Know About Ruby
                      http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
mensajes. method_missing
class VCR
  def initialize
    @messages = []
  end
  def method_missing(method, *args, &block)
    @messages << [method, args, block]
  end
  def play_back_to(obj)
    @messages.each do |method, args, block|
      obj.send(method, *args, &block)
    end
  end
end
       Proxies, Auto Loaders, Decorators, Mock Objects, Builders...

                          fuente: 10 Things Every Java Programmer Should Know About Ruby
                          http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
tipos
fuertemente tipado, a
diferencia de C y de igual                 class Duck
forma que en JAVA                            def talk() puts
                                           "Quack" end
                                           end
                                           class DuckLikeObject
tipos asignados implícitamente               def talk() puts "Kwak"
                                           end
y comprobados dinámicamente                end
en tiempo de ejecución (late               flock = [
binding)                                     Duck.new,
                                             DuckLikeObject.new ]
                                           flock.each do |d| d.talk
                                           end
duck typing. “if it walks like a
duck and talks like a duck, we
can treat it as a duck”

                      fuente: 10 Things Every Java Programmer Should Know About Ruby
                      http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
tipos. algunas implicaciones
def factorial(n)              public class Fact {
  result = 1                    static long factorial(long n) {
  (2..n).each do |i|              long result = 1;
    result *= i                   for (long i=2; i<=n; i++)
  end                               result *= i;
  result                          return result;
end                             }
                                public static
puts factorial(20)                void main (String args[]) {
puts factorial(21)
                              System.out.println(factorial(20))
                              ;
2432902008176640000
51090942171709440000          System.out.println(factorial(21))
                              ;
                                }
                              }
                              2432902008176640000
                              -4249290049419214848


                       fuente: 10 Things Every Java Programmer Should Know About Ruby
                       http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
bloques (closures)
Iteradores
    [1,2,3].each do |item|
      puts item
    end
Gestión de recursos
 file_contents = open(file_or_url_name) { |f|
f.read }

Callbacks
 widget.on_button_press { puts "Press!" }



                      fuente: 10 Things Every Java Programmer Should Know About Ruby
                      http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
domain specific languages
Feature: Hello                           class User < ActiveRecord::Base

  In order to have more friends                has_one :address

  I want to say hello                          belongs_to :company

  Scenario: Personal greeting                  has_many :items

    Given my name is Aslak

    When I greet David                      validates_presence_of
                                         :name, :email
    Then he should hear Hi, David. I'm
Aslak.                                   end

    And I should remember David as a
friend

    And I should get David's phone
number




                                          fuente: http://github.com/aslakhellesoy/cucumber
utilidades (muy útiles!)
ri String#upcase
   ----------------------------------------------------------
String#upcase               str.upcase   => new_str
-----------------------------------------------------------------
     Returns a copy of _str_ with all lowercase letters replaced with
     their uppercase counterparts. The operation is locale
     insensitive---only characters ``a'' to ``z'' are affected.
        "hEllO".upcase   #=> "HELLO"

irb
en Ruby todo el código es ejecutable y devuelve un resultado,
incluyendo las definiciones de clases, métodos, sentencias de
control...

rubygems, rake, capistrano, chef, cucumber...
http://rubyonrails.org
ruby on rails

Desarrollado por David Heinemeier Hansson,
comenzando en 2003. Primera release estable en
julio de 2004. Versión 1.0 en diciembre de 2005.
La versión actual es 2.3.2 (con rails 3 en versión
unstable)
“Ruby on Rails is an open-source web framework
that's optimized for programmer happiness and
sustainable productivity. It lets you write beautiful
code by favoring convention over configuration”
open source

Mejorado por la comunidad. 1391 personas han
enviado contribuciones al core. 200 personas en lo
que va de año
Son contribuciones “voluntarias” (no controladas
por empresas). Se gana acceso al core por méritos

Incontables plugins, gemas y librerías en rubyforge,
github, sourceforge y code.google.com



                                  fuente: http://contributors.rubyonrails.org/
extracted, not built

Desarrollado a partir de una aplicación real
(Basecamp)
Los grandes bloques de funcionalidad se añaden a
partir de plugins, gemas o librerías que tienen una
adopción grande por la comunidad (ejemplo:
REST, merb, i18n)
Si una funcionalidad no se usa demasiado, se
extrae del core y se deja disponible como plugin
(acts_as_tree, acts_as_list)
full-stack framework


Framework "full-stack"
de desarrollo para
aplicaciones web,
siguiendo el patrón
MVC
full-stack framework
Controladores
Vistas (+AJAX)
Modelos
Persistencia (validaciones)
E-mail
REST
Rutas
XML
Testing
Tareas


                         imagen: http://craphound.com/images/hellovader.jpg
principios de diseño
 Principio de la mínima sorpresa
 Principio de Brevedad
 Principio de la Interfaz Humana
 DRY (Don't repeat yourself)
 COC (Convention over configuration)
 Agile (no deploy, generators, testing)
arquitectura / flujo

          RACK
miniaplicación REST desde cero
gem install rails
rails myapp
cd myapp
#configura la conexión de tu db en config/database.yml
rake db:create:all #si la db no existe todavía
#generamos migration, rutas, modelo, vista, controller, tests y fixtures
ruby script/generate scaffold post title:string body:text published:boolean
rake db:migrate #ejecuta la migration y crea la tabla
ruby script/server #en http://localhost:3000/posts podemos ver la aplicación
rake #carga la base de datos de testing y ejecuta los tests
prototipo generado
migration
modelo
 class Post < ActiveRecord::Base
 end



  Post.find_all_by_published true
 => [#<Post id: 1, title: "hello java and ruby world", body:
 "this is just a test of what you can do", published: true,
 created_at: "2009-06-10 00:03:37", updated_at: "2009-06-10
 00:03:37">]
 >> Post.last
 => #<Post id: 1, title: "hello java and ruby world", body:
 "this is just a test of what you can do", published: true,
 created_at: "2009-06-10 00:03:37", updated_at: "2009-06-10
 00:03:37">


 >> Post.first.valid?
 => true
rutas y controlador


config/routes.rb
map.resources :posts
vistas
tests
           funcionales

fixtures




               unitarios
deployment con rails

basado en recetas escritas en ruby:
capistrano, vlad, chef


Servidores
Apache/Nginx + passenger
Apache/Nginx + mongrel_cluster
http://jruby.org
jruby

Iniciado por Jan Arne Petersen, en 2001, open
source
Unos 50 contribuidores al proyecto
En 2006, Charles Nutter y Thomas Enebo son
contratados por SUN
Core actual: 8 desarrolladores
jruby
JRuby es una implementación 100% Java del
lenguaje de programación Ruby. Es Ruby para la
JVM (fuente: jruby.org)

Implementaciones Ruby: MRI, Jruby, IronRuby,
MacRuby, Ruby.NET, MagLev, Rubinius

No hay especificación (http://rubyspec.org/)
java como plataforma
 La JVM está muy optimizada y sigue mejorando
 Omnipresente, multiplataforma
 Garbage Collector potente y configurable
 Threads
 Monitorización
 Librerías
 Compilación a ByteCode (AOT/JIT)
java como plataforma

Aplicaciones Rails desplegadas sobre cualquier
Java Application Server

Menor resistencia en sitios con aplicaciones
Java

“Credibilidad por Asociación” (Ola Bini)
retos

IRB                       POSIX
rubygems                  Librerías Nativas (FFI)
YAML                      IO (ficheros, sockets, pipes...)
Zlib                      Rendimiento
Rails                     Compilación a ByteCode
ActiveRecord-JDBC         Tipos
Strings
RegExps eficientes




                     fuente: Beyond Impossible, How Jruby evolved the Java Platform
                     talk by Charles Nutter at Community One 2009
java desde ruby
require 'java'

frame = javax.swing.JFrame.new("Window")
label = javax.swing.JLabel.new("Hello")
frame.get_content_pane.add(label)   #'getContentPane'.
#setDefaultCloseOperation()
frame.default_close_operation =
               javax.swing.JFrame::DISPOSE_ON_CLOSE
frame.pack
frame.setVisible(true)
java desde ruby
java.net.NetworkInterface.networkInterfaces.each{|i| puts I}
java.net.NetworkInterface.networkInterfaces.methods.grep /element/
[1, 2, 3.5].to_java Java::double
  => [D@9bc984
DoSomethingWithJavaClass(MyJavaClass.java_class)

class SomeJRubyObject
    include java.lang.Runnable
    include java.lang.Comparable
end
button = javax.swing.JButton.new "Press me!"
button.add_action_listener {|event| event.source.text = "YES!"}
java es dinámico (si sabes cómo)
jsr 223 scripting API
import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception
{
      ScriptEngineManager factory = new
ScriptEngineManager();
      // Create a JRuby engine.
      ScriptEngine engine =
factory.getEngineByName("jruby");
      // Evaluate JRuby code from string.
      try {
        engine.eval("puts('Hello')");
      } catch (ScriptException exception) {
        exception.printStackTrace();
      }
    }
}
jsr 223 scripting API
Invocable inv = (Invocable) engine;
Object obj = null;
try {
    FileReader f = new FileReader("wadus.rb");
    engine.eval(f);
} catch (javax.script.ScriptException e) {
    System.out.println("Script Exception");
} catch(java.io.FileNotFoundException e) {
    e.printStackTrace();
}
try {
       obj=inv.invokeFunction("say_wadus", params);
       } catch (javax.script.ScriptException e) {
     e.printStackTrace();
       } catch (java.lang.NoSuchMethodException e) {
            e.printStackTrace();
  }
System.out.println(obj.toString());

                           #wadus.rb
                           def say_wadus
                              “wadus”
                           end
jakarta bsf
import org.apache.bsf.*;
public class BSF {
 public static void main(String[] args) throws Exception {
    // Create a script manager.
    BSFManager bsfmanager=new BSFManager();
    // Evaluate the ruby expression.
    try {
      bsfmanager.eval("ruby","Test",0,0,"puts('Hello')");
    } catch (BSFException exception) {
      exception.printStackTrace();
    }
}
despliegue sobre la JVM

jgem install warbler
jruby -S warble config
jruby -S warble war

WEB-INF y .war standard listos para deploy
(perfecto en producción, poco ágil en desarrollo)
despliegue sobre la JVM

jgem install mongrel_rails #mongrel_rails start
jgem install glassfish #glassfish_rails
jgem install calavera-tomcat-rails #tomcat_rails


permite cambios en caliente
JRuby on Rails
Ruby on Rails sobre la JVM


                                                                                    javier ramírez


http://aspgems.com                                                http://spainrb.org/javier-ramirez

obra publicada por javier ramirez como ‘Atribución-No Comercial-Licenciar Igual 2.5’ de Creative Commons

Weitere ähnliche Inhalte

Was ist angesagt?

¿Porqué Python? ...y Django
¿Porqué Python? ...y Django¿Porqué Python? ...y Django
¿Porqué Python? ...y DjangoAntonio Ognio
 
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?Micael Gallego
 
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casa
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casaTypeScript para Javeros: Cómo programar web front-end y sentirse como en casa
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casaMicael Gallego
 
Symfony2: Framework para PHP5
Symfony2: Framework para PHP5Symfony2: Framework para PHP5
Symfony2: Framework para PHP5Raul Fraile
 
Iniciación PHP 5. Introducción
Iniciación PHP 5. IntroducciónIniciación PHP 5. Introducción
Iniciación PHP 5. IntroducciónRightster
 
Introducción a PHP - Programador PHP - UGR
Introducción a PHP - Programador PHP - UGRIntroducción a PHP - Programador PHP - UGR
Introducción a PHP - Programador PHP - UGRJuan Belón Pérez
 
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript David Ballén
 
Desarrollo de aplicaciones web con PHP y symfony
Desarrollo de aplicaciones web con PHP y symfonyDesarrollo de aplicaciones web con PHP y symfony
Desarrollo de aplicaciones web con PHP y symfonyJuan Eladio Sánchez Rosas
 
Curso Avanzado PHP para EHU/UPV
Curso Avanzado PHP para EHU/UPVCurso Avanzado PHP para EHU/UPV
Curso Avanzado PHP para EHU/UPVIrontec
 
Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5Raul Fraile
 
Zen Scaffolding - Programador PHP
Zen Scaffolding - Programador PHPZen Scaffolding - Programador PHP
Zen Scaffolding - Programador PHPJuan Belón Pérez
 
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browser
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browserTypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browser
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browserMicael Gallego
 

Was ist angesagt? (20)

¿Porqué Python? ...y Django
¿Porqué Python? ...y Django¿Porqué Python? ...y Django
¿Porqué Python? ...y Django
 
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?
JavaScript para Javeros. ¿Cómo ser moderno y no morir en el intento?
 
Python 4
Python 4Python 4
Python 4
 
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casa
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casaTypeScript para Javeros: Cómo programar web front-end y sentirse como en casa
TypeScript para Javeros: Cómo programar web front-end y sentirse como en casa
 
Symfony2: Framework para PHP5
Symfony2: Framework para PHP5Symfony2: Framework para PHP5
Symfony2: Framework para PHP5
 
Java Basico Platzi
Java Basico PlatziJava Basico Platzi
Java Basico Platzi
 
Iniciación PHP 5. Introducción
Iniciación PHP 5. IntroducciónIniciación PHP 5. Introducción
Iniciación PHP 5. Introducción
 
Introducción a PHP - Programador PHP - UGR
Introducción a PHP - Programador PHP - UGRIntroducción a PHP - Programador PHP - UGR
Introducción a PHP - Programador PHP - UGR
 
Curso Php
Curso PhpCurso Php
Curso Php
 
Composer: Gestionando dependencias en PHP
Composer: Gestionando dependencias en PHP Composer: Gestionando dependencias en PHP
Composer: Gestionando dependencias en PHP
 
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript
Mejorando.la: Curso Profesional de Frontend, Dominando JavaScript
 
Desarrollo de aplicaciones web con PHP y symfony
Desarrollo de aplicaciones web con PHP y symfonyDesarrollo de aplicaciones web con PHP y symfony
Desarrollo de aplicaciones web con PHP y symfony
 
Curso Avanzado PHP para EHU/UPV
Curso Avanzado PHP para EHU/UPVCurso Avanzado PHP para EHU/UPV
Curso Avanzado PHP para EHU/UPV
 
Java 1.8:Road to Functional Language
Java 1.8:Road to Functional LanguageJava 1.8:Road to Functional Language
Java 1.8:Road to Functional Language
 
Mockito
MockitoMockito
Mockito
 
Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5
 
Zen Scaffolding - Programador PHP
Zen Scaffolding - Programador PHPZen Scaffolding - Programador PHP
Zen Scaffolding - Programador PHP
 
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browser
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browserTypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browser
TypeScript para Javeros. Por fin un lenguaje 'de verdad' en el browser
 
Destructores
Destructores Destructores
Destructores
 
Unidad 2. Lenguaje orientado a objetos
Unidad 2. Lenguaje orientado a objetosUnidad 2. Lenguaje orientado a objetos
Unidad 2. Lenguaje orientado a objetos
 

Ähnlich wie Jruby On Rails. Ruby on Rails en la JVM

Programación Políglota en la JVM
Programación Políglota en la JVMProgramación Políglota en la JVM
Programación Políglota en la JVMJano González
 
Presentacion Ruby on Rails CTIC-Cusco2007
Presentacion Ruby on Rails CTIC-Cusco2007Presentacion Ruby on Rails CTIC-Cusco2007
Presentacion Ruby on Rails CTIC-Cusco2007JuancaPompilla
 
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011Jano González
 
Ruby On Rails Jun2009
Ruby On Rails Jun2009Ruby On Rails Jun2009
Ruby On Rails Jun2009Sergio Alonso
 
JRuby: Ruby en un mundo enterprise
JRuby: Ruby en un mundo enterpriseJRuby: Ruby en un mundo enterprise
JRuby: Ruby en un mundo enterpriseJano González
 
Meetup training Taller RoR
Meetup training Taller RoR Meetup training Taller RoR
Meetup training Taller RoR cdechauri
 
Ruby on the Rails
Ruby on the RailsRuby on the Rails
Ruby on the Rails000ari2014
 
Fundamento de poo en php
Fundamento de poo en phpFundamento de poo en php
Fundamento de poo en phpRobert Moreira
 
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARLa Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARPablo Godel
 
Nodejs.introduccion
Nodejs.introduccionNodejs.introduccion
Nodejs.introduccionkillfill
 
Sesión 03: Ruby y SAP
Sesión 03: Ruby y SAPSesión 03: Ruby y SAP
Sesión 03: Ruby y SAPBiz Partner
 

Ähnlich wie Jruby On Rails. Ruby on Rails en la JVM (20)

Ruby para Java Developers
Ruby para Java DevelopersRuby para Java Developers
Ruby para Java Developers
 
Programación Políglota en la JVM
Programación Políglota en la JVMProgramación Políglota en la JVM
Programación Políglota en la JVM
 
Presentacion Ruby on Rails CTIC-Cusco2007
Presentacion Ruby on Rails CTIC-Cusco2007Presentacion Ruby on Rails CTIC-Cusco2007
Presentacion Ruby on Rails CTIC-Cusco2007
 
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011
JRuby: Ruby en un mundo enterprise RubyConf Uruguay 2011
 
Ruby On Rails Jun2009
Ruby On Rails Jun2009Ruby On Rails Jun2009
Ruby On Rails Jun2009
 
Jano Gonzalez - jruby
Jano Gonzalez - jrubyJano Gonzalez - jruby
Jano Gonzalez - jruby
 
JRuby: Ruby en un mundo enterprise
JRuby: Ruby en un mundo enterpriseJRuby: Ruby en un mundo enterprise
JRuby: Ruby en un mundo enterprise
 
Meetup training Taller RoR
Meetup training Taller RoR Meetup training Taller RoR
Meetup training Taller RoR
 
Ruby on the Rails
Ruby on the RailsRuby on the Rails
Ruby on the Rails
 
Fundamento de poo en php
Fundamento de poo en phpFundamento de poo en php
Fundamento de poo en php
 
Java
JavaJava
Java
 
Docker ECS en AWS
Docker ECS en AWS Docker ECS en AWS
Docker ECS en AWS
 
Java jaucito
Java jaucitoJava jaucito
Java jaucito
 
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARLa Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
 
Ruby intro
Ruby introRuby intro
Ruby intro
 
Nodejs.introduccion
Nodejs.introduccionNodejs.introduccion
Nodejs.introduccion
 
sesion_01-JAVA.pdf
sesion_01-JAVA.pdfsesion_01-JAVA.pdf
sesion_01-JAVA.pdf
 
C1 java introduccion
C1 java introduccionC1 java introduccion
C1 java introduccion
 
C1 java introduccion
C1 java introduccionC1 java introduccion
C1 java introduccion
 
Sesión 03: Ruby y SAP
Sesión 03: Ruby y SAPSesión 03: Ruby y SAP
Sesión 03: Ruby y SAP
 

Mehr von javier ramirez

¿Se puede vivir del open source? T3chfest
¿Se puede vivir del open source? T3chfest¿Se puede vivir del open source? T3chfest
¿Se puede vivir del open source? T3chfestjavier ramirez
 
QuestDB: The building blocks of a fast open-source time-series database
QuestDB: The building blocks of a fast open-source time-series databaseQuestDB: The building blocks of a fast open-source time-series database
QuestDB: The building blocks of a fast open-source time-series databasejavier ramirez
 
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...javier ramirez
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...javier ramirez
 
Deduplicating and analysing time-series data with Apache Beam and QuestDB
Deduplicating and analysing time-series data with Apache Beam and QuestDBDeduplicating and analysing time-series data with Apache Beam and QuestDB
Deduplicating and analysing time-series data with Apache Beam and QuestDBjavier ramirez
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)javier ramirez
 
Your Timestamps Deserve Better than a Generic Database
Your Timestamps Deserve Better than a Generic DatabaseYour Timestamps Deserve Better than a Generic Database
Your Timestamps Deserve Better than a Generic Databasejavier ramirez
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...javier ramirez
 
QuestDB-Community-Call-20220728
QuestDB-Community-Call-20220728QuestDB-Community-Call-20220728
QuestDB-Community-Call-20220728javier ramirez
 
Processing and analysing streaming data with Python. Pycon Italy 2022
Processing and analysing streaming  data with Python. Pycon Italy 2022Processing and analysing streaming  data with Python. Pycon Italy 2022
Processing and analysing streaming data with Python. Pycon Italy 2022javier ramirez
 
QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...javier ramirez
 
Servicios e infraestructura de AWS y la próxima región en Aragón
Servicios e infraestructura de AWS y la próxima región en AragónServicios e infraestructura de AWS y la próxima región en Aragón
Servicios e infraestructura de AWS y la próxima región en Aragónjavier ramirez
 
Primeros pasos en desarrollo serverless
Primeros pasos en desarrollo serverlessPrimeros pasos en desarrollo serverless
Primeros pasos en desarrollo serverlessjavier ramirez
 
How AWS is reinventing the cloud
How AWS is reinventing the cloudHow AWS is reinventing the cloud
How AWS is reinventing the cloudjavier ramirez
 
Analitica de datos en tiempo real con Apache Flink y Apache BEAM
Analitica de datos en tiempo real con Apache Flink y Apache BEAMAnalitica de datos en tiempo real con Apache Flink y Apache BEAM
Analitica de datos en tiempo real con Apache Flink y Apache BEAMjavier ramirez
 
Getting started with streaming analytics
Getting started with streaming analyticsGetting started with streaming analytics
Getting started with streaming analyticsjavier ramirez
 
Getting started with streaming analytics: Setting up a pipeline
Getting started with streaming analytics: Setting up a pipelineGetting started with streaming analytics: Setting up a pipeline
Getting started with streaming analytics: Setting up a pipelinejavier ramirez
 
Getting started with streaming analytics: Deep Dive
Getting started with streaming analytics: Deep DiveGetting started with streaming analytics: Deep Dive
Getting started with streaming analytics: Deep Divejavier ramirez
 
Getting started with streaming analytics: streaming basics (1 of 3)
Getting started with streaming analytics: streaming basics (1 of 3)Getting started with streaming analytics: streaming basics (1 of 3)
Getting started with streaming analytics: streaming basics (1 of 3)javier ramirez
 
Monitorización de seguridad y detección de amenazas con AWS
Monitorización de seguridad y detección de amenazas con AWSMonitorización de seguridad y detección de amenazas con AWS
Monitorización de seguridad y detección de amenazas con AWSjavier ramirez
 

Mehr von javier ramirez (20)

¿Se puede vivir del open source? T3chfest
¿Se puede vivir del open source? T3chfest¿Se puede vivir del open source? T3chfest
¿Se puede vivir del open source? T3chfest
 
QuestDB: The building blocks of a fast open-source time-series database
QuestDB: The building blocks of a fast open-source time-series databaseQuestDB: The building blocks of a fast open-source time-series database
QuestDB: The building blocks of a fast open-source time-series database
 
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
 
Deduplicating and analysing time-series data with Apache Beam and QuestDB
Deduplicating and analysing time-series data with Apache Beam and QuestDBDeduplicating and analysing time-series data with Apache Beam and QuestDB
Deduplicating and analysing time-series data with Apache Beam and QuestDB
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)
 
Your Timestamps Deserve Better than a Generic Database
Your Timestamps Deserve Better than a Generic DatabaseYour Timestamps Deserve Better than a Generic Database
Your Timestamps Deserve Better than a Generic Database
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
 
QuestDB-Community-Call-20220728
QuestDB-Community-Call-20220728QuestDB-Community-Call-20220728
QuestDB-Community-Call-20220728
 
Processing and analysing streaming data with Python. Pycon Italy 2022
Processing and analysing streaming  data with Python. Pycon Italy 2022Processing and analysing streaming  data with Python. Pycon Italy 2022
Processing and analysing streaming data with Python. Pycon Italy 2022
 
QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...
 
Servicios e infraestructura de AWS y la próxima región en Aragón
Servicios e infraestructura de AWS y la próxima región en AragónServicios e infraestructura de AWS y la próxima región en Aragón
Servicios e infraestructura de AWS y la próxima región en Aragón
 
Primeros pasos en desarrollo serverless
Primeros pasos en desarrollo serverlessPrimeros pasos en desarrollo serverless
Primeros pasos en desarrollo serverless
 
How AWS is reinventing the cloud
How AWS is reinventing the cloudHow AWS is reinventing the cloud
How AWS is reinventing the cloud
 
Analitica de datos en tiempo real con Apache Flink y Apache BEAM
Analitica de datos en tiempo real con Apache Flink y Apache BEAMAnalitica de datos en tiempo real con Apache Flink y Apache BEAM
Analitica de datos en tiempo real con Apache Flink y Apache BEAM
 
Getting started with streaming analytics
Getting started with streaming analyticsGetting started with streaming analytics
Getting started with streaming analytics
 
Getting started with streaming analytics: Setting up a pipeline
Getting started with streaming analytics: Setting up a pipelineGetting started with streaming analytics: Setting up a pipeline
Getting started with streaming analytics: Setting up a pipeline
 
Getting started with streaming analytics: Deep Dive
Getting started with streaming analytics: Deep DiveGetting started with streaming analytics: Deep Dive
Getting started with streaming analytics: Deep Dive
 
Getting started with streaming analytics: streaming basics (1 of 3)
Getting started with streaming analytics: streaming basics (1 of 3)Getting started with streaming analytics: streaming basics (1 of 3)
Getting started with streaming analytics: streaming basics (1 of 3)
 
Monitorización de seguridad y detección de amenazas con AWS
Monitorización de seguridad y detección de amenazas con AWSMonitorización de seguridad y detección de amenazas con AWS
Monitorización de seguridad y detección de amenazas con AWS
 

Kürzlich hochgeladen

PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxAlan779941
 
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdfRefrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdfvladimiroflores1
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.FlorenciaCattelani
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITMaricarmen Sánchez Ruiz
 
Modulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdfModulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdfAnnimoUno1
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanamcerpam
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21mariacbr99
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...JohnRamos830530
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxJorgeParada26
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estossgonzalezp1
 
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxEL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxMiguelAtencio10
 

Kürzlich hochgeladen (11)

PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
 
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdfRefrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
Modulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdfModulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdf
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxEL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
 

Jruby On Rails. Ruby on Rails en la JVM

  • 1. JRuby on Rails Ruby on Rails sobre la JVM javier ramírez http://aspgems.com http://spainrb.org/javier-ramirez obra publicada por javier ramirez como ‘Atribución-No Comercial-Licenciar Igual 2.5’ de Creative Commons
  • 3. james duncan davidson Servlet API, Tomcat, Ant, Java API for XML Processing
  • 4. james duncan davidson Servlet API, Tomcat, Ant, Java API for XML Processing Rails is the most well thought-out web development framework I’ve ever used. And that’s in a decade of doing web applications for a living. I’ve built my own frameworks, helped develop the Servlet API, and have created more than a few web servers from scratch. Nobody has done it like this before.
  • 5. qué Ruby, el lenguaje Rails, el framework JRuby, la plataforma
  • 6. self http://aspgems.com http://formatinternet.com http://javier.github.com http://spainrb.org/javier-ramirez jramirez@aspgems.com http://twitter.com/supercoco9
  • 8. tolerancia al dolor I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark...
  • 9. tolerancia al dolor I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark... He perdido horas en altavista.com buscando cómo escribir Blobs en DB2 con JDBC
  • 10. tolerancia al dolor I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark... He perdido horas en altavista.com buscando cómo escribir Blobs en DB2 con JDBC JDK 1.0 JAVA 2 RMI/CORBA JNI LDAP JNDI SAX DOM STAX EJB1 (sin interfaz local) EJB2 Jlex SOAP JSP XSLT Freemarker
  • 11. tolerancia al dolor I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark... He perdido horas en altavista.com buscando cómo escribir Blobs en DB2 con JDBC JDK 1.0 JAVA 2 RMI/CORBA JNI LDAP JNDI SAX DOM STAX EJB1 (sin interfaz local) EJB2 Jlex SOAP JSP XSLT Freemarker Bancos, Administración Pública, Farmaceúticas, SGAE...
  • 13. ruby Creado por Yukihiro Matsumoto aka “Matz” Dinámico, Orientado a Objetos y Open Source Primera versión de desarrollo en 1993 Primera versión oficial en 1995 foto con licencia creative commons por Javier Vidal Postigo fuente: flickr
  • 14. así que desde 1995... ¿Y cómo es que no supe nada de ruby hasta mucho más tarde?
  • 15. 1995 2002
  • 16. ¿por qué un nuevo lenguaje? Hipótesis de Sapir-Whorf: todos los pensamientos teóricos están basados en el lenguaje y están condicionados por él fuente: wikipedia
  • 17. ¿por qué un nuevo lenguaje? Hipótesis de Sapir-Whorf: todos los pensamientos teóricos están basados en el lenguaje y están condicionados por él Los diferentes lenguajes de programación, condicionan la forma en que los programadores desarrollan sus soluciones fuente: the power and philosophy of ruby http://www.rubyist.net/~matz/slides/oscon2003/
  • 18. ¿por qué ruby? Diseñado para ser divertido, creativo, y reducir el estrés del programador. Centrado en la resolución de problemas fuente: the power and philosophy of ruby http://www.rubyist.net/~matz/slides/oscon2003/
  • 19. ¿por qué ruby? Diseñado para ser divertido, creativo, y reducir el estrés del programador. Centrado en la resolución de problemas Las personas son buenas Las personas no son en buenas en •Creatividad •hacer copias •Imaginación •trabajos rutinarios •Resolución de problemas •cálculos, etc… fuente: the power and philosophy of ruby http://www.rubyist.net/~matz/slides/oscon2003/
  • 20. principios de diseño principio de la mínima sorpresa principio de la brevedad (succinctness) principio de la interfaz humana enviar mensajes “ocultos” (syntactic sugar) fuente: the power and philosophy of ruby http://www.rubyist.net/~matz/slides/oscon2003/
  • 21. convenciones en ruby ClassNames method_names and variable_names methods_asking_a_question? slightly_dangerous_methods! @instance_variables $global_variables SOME_CONSTANTS or OtherConstants fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 22. orientación “pura” a objetos Alan Kay Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind
  • 23. orientación “pura” a objetos Alan Kay (2003) Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late- binding of all things. It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but I'm not aware of them fuente: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en
  • 24. todo es un objeto las clases son objetos => Array.new ejemplo de factoría en ruby def create_from_factory(factory) factory.new end obj = create_from_factory(Array) fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 25. nil es un objeto nil.nil? => true nil.methods.grep /?/ => ["instance_variable_defined?", "equal?", "respond_to?", "eql?", "frozen?", "instance_of?", "kind_of?", "tainted?", "nil?", "is_a?"]
  • 26. todo es un objeto.sin primitivas 0.zero? # => true true.class #=> TrueClass 1.zero? # => false 1.abs # => 1 -1.abs # => 1 1.methods # => métodos del objeto 1 2.+(3) # => 5 (igual que 2+3) 10.class # => Fixnum (10**100).class # => Bignum Bignum.class # => Class (1..20).class #=> Range fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 27. dinámico Reflection muy simple Clases Abiertas Objetos Singleton Hooks integrados Evaluación dinámica Mensajes dinámicos ObjectSpace fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 28. dinámico. ejemplos def create(klass, value) class MyClass def MyClass.method_added(name) klass.new(value) puts "Adding Method #{name}" end end create(Greeting, "Hello") def new_method # Yada yada yada class Integer end def even? end (self % 2) == 0 end end 3.even? => false fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 29. mensajes. method_missing class VCR def initialize @messages = [] end def method_missing(method, *args, &block) @messages << [method, args, block] end def play_back_to(obj) @messages.each do |method, args, block| obj.send(method, *args, &block) end end end Proxies, Auto Loaders, Decorators, Mock Objects, Builders... fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 30. tipos fuertemente tipado, a diferencia de C y de igual class Duck forma que en JAVA def talk() puts "Quack" end end class DuckLikeObject tipos asignados implícitamente def talk() puts "Kwak" end y comprobados dinámicamente end en tiempo de ejecución (late flock = [ binding) Duck.new, DuckLikeObject.new ] flock.each do |d| d.talk end duck typing. “if it walks like a duck and talks like a duck, we can treat it as a duck” fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 31. tipos. algunas implicaciones def factorial(n) public class Fact { result = 1 static long factorial(long n) { (2..n).each do |i| long result = 1; result *= i for (long i=2; i<=n; i++) end result *= i; result return result; end } public static puts factorial(20) void main (String args[]) { puts factorial(21) System.out.println(factorial(20)) ; 2432902008176640000 51090942171709440000 System.out.println(factorial(21)) ; } } 2432902008176640000 -4249290049419214848 fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 32. bloques (closures) Iteradores [1,2,3].each do |item| puts item end Gestión de recursos file_contents = open(file_or_url_name) { |f| f.read } Callbacks widget.on_button_press { puts "Press!" } fuente: 10 Things Every Java Programmer Should Know About Ruby http://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
  • 33. domain specific languages Feature: Hello class User < ActiveRecord::Base In order to have more friends has_one :address I want to say hello belongs_to :company Scenario: Personal greeting has_many :items Given my name is Aslak When I greet David validates_presence_of :name, :email Then he should hear Hi, David. I'm Aslak. end And I should remember David as a friend And I should get David's phone number fuente: http://github.com/aslakhellesoy/cucumber
  • 34. utilidades (muy útiles!) ri String#upcase ---------------------------------------------------------- String#upcase str.upcase => new_str ----------------------------------------------------------------- Returns a copy of _str_ with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive---only characters ``a'' to ``z'' are affected. "hEllO".upcase #=> "HELLO" irb en Ruby todo el código es ejecutable y devuelve un resultado, incluyendo las definiciones de clases, métodos, sentencias de control... rubygems, rake, capistrano, chef, cucumber...
  • 36. ruby on rails Desarrollado por David Heinemeier Hansson, comenzando en 2003. Primera release estable en julio de 2004. Versión 1.0 en diciembre de 2005. La versión actual es 2.3.2 (con rails 3 en versión unstable) “Ruby on Rails is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration”
  • 37. open source Mejorado por la comunidad. 1391 personas han enviado contribuciones al core. 200 personas en lo que va de año Son contribuciones “voluntarias” (no controladas por empresas). Se gana acceso al core por méritos Incontables plugins, gemas y librerías en rubyforge, github, sourceforge y code.google.com fuente: http://contributors.rubyonrails.org/
  • 38. extracted, not built Desarrollado a partir de una aplicación real (Basecamp) Los grandes bloques de funcionalidad se añaden a partir de plugins, gemas o librerías que tienen una adopción grande por la comunidad (ejemplo: REST, merb, i18n) Si una funcionalidad no se usa demasiado, se extrae del core y se deja disponible como plugin (acts_as_tree, acts_as_list)
  • 39. full-stack framework Framework "full-stack" de desarrollo para aplicaciones web, siguiendo el patrón MVC
  • 40. full-stack framework Controladores Vistas (+AJAX) Modelos Persistencia (validaciones) E-mail REST Rutas XML Testing Tareas imagen: http://craphound.com/images/hellovader.jpg
  • 41. principios de diseño Principio de la mínima sorpresa Principio de Brevedad Principio de la Interfaz Humana DRY (Don't repeat yourself) COC (Convention over configuration) Agile (no deploy, generators, testing)
  • 43. miniaplicación REST desde cero gem install rails rails myapp cd myapp #configura la conexión de tu db en config/database.yml rake db:create:all #si la db no existe todavía #generamos migration, rutas, modelo, vista, controller, tests y fixtures ruby script/generate scaffold post title:string body:text published:boolean rake db:migrate #ejecuta la migration y crea la tabla ruby script/server #en http://localhost:3000/posts podemos ver la aplicación rake #carga la base de datos de testing y ejecuta los tests
  • 46. modelo class Post < ActiveRecord::Base end Post.find_all_by_published true => [#<Post id: 1, title: "hello java and ruby world", body: "this is just a test of what you can do", published: true, created_at: "2009-06-10 00:03:37", updated_at: "2009-06-10 00:03:37">] >> Post.last => #<Post id: 1, title: "hello java and ruby world", body: "this is just a test of what you can do", published: true, created_at: "2009-06-10 00:03:37", updated_at: "2009-06-10 00:03:37"> >> Post.first.valid? => true
  • 49. tests funcionales fixtures unitarios
  • 50. deployment con rails basado en recetas escritas en ruby: capistrano, vlad, chef Servidores Apache/Nginx + passenger Apache/Nginx + mongrel_cluster
  • 52. jruby Iniciado por Jan Arne Petersen, en 2001, open source Unos 50 contribuidores al proyecto En 2006, Charles Nutter y Thomas Enebo son contratados por SUN Core actual: 8 desarrolladores
  • 53. jruby JRuby es una implementación 100% Java del lenguaje de programación Ruby. Es Ruby para la JVM (fuente: jruby.org) Implementaciones Ruby: MRI, Jruby, IronRuby, MacRuby, Ruby.NET, MagLev, Rubinius No hay especificación (http://rubyspec.org/)
  • 54. java como plataforma La JVM está muy optimizada y sigue mejorando Omnipresente, multiplataforma Garbage Collector potente y configurable Threads Monitorización Librerías Compilación a ByteCode (AOT/JIT)
  • 55. java como plataforma Aplicaciones Rails desplegadas sobre cualquier Java Application Server Menor resistencia en sitios con aplicaciones Java “Credibilidad por Asociación” (Ola Bini)
  • 56. retos IRB POSIX rubygems Librerías Nativas (FFI) YAML IO (ficheros, sockets, pipes...) Zlib Rendimiento Rails Compilación a ByteCode ActiveRecord-JDBC Tipos Strings RegExps eficientes fuente: Beyond Impossible, How Jruby evolved the Java Platform talk by Charles Nutter at Community One 2009
  • 57. java desde ruby require 'java' frame = javax.swing.JFrame.new("Window") label = javax.swing.JLabel.new("Hello") frame.get_content_pane.add(label) #'getContentPane'. #setDefaultCloseOperation() frame.default_close_operation = javax.swing.JFrame::DISPOSE_ON_CLOSE frame.pack frame.setVisible(true)
  • 58. java desde ruby java.net.NetworkInterface.networkInterfaces.each{|i| puts I} java.net.NetworkInterface.networkInterfaces.methods.grep /element/ [1, 2, 3.5].to_java Java::double => [D@9bc984 DoSomethingWithJavaClass(MyJavaClass.java_class) class SomeJRubyObject include java.lang.Runnable include java.lang.Comparable end button = javax.swing.JButton.new "Press me!" button.add_action_listener {|event| event.source.text = "YES!"}
  • 59. java es dinámico (si sabes cómo)
  • 60. jsr 223 scripting API import javax.script.*; public class EvalScript { public static void main(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); // Create a JRuby engine. ScriptEngine engine = factory.getEngineByName("jruby"); // Evaluate JRuby code from string. try { engine.eval("puts('Hello')"); } catch (ScriptException exception) { exception.printStackTrace(); } } }
  • 61. jsr 223 scripting API Invocable inv = (Invocable) engine; Object obj = null; try { FileReader f = new FileReader("wadus.rb"); engine.eval(f); } catch (javax.script.ScriptException e) { System.out.println("Script Exception"); } catch(java.io.FileNotFoundException e) { e.printStackTrace(); } try { obj=inv.invokeFunction("say_wadus", params); } catch (javax.script.ScriptException e) { e.printStackTrace(); } catch (java.lang.NoSuchMethodException e) { e.printStackTrace(); } System.out.println(obj.toString()); #wadus.rb def say_wadus “wadus” end
  • 62. jakarta bsf import org.apache.bsf.*; public class BSF { public static void main(String[] args) throws Exception { // Create a script manager. BSFManager bsfmanager=new BSFManager(); // Evaluate the ruby expression. try { bsfmanager.eval("ruby","Test",0,0,"puts('Hello')"); } catch (BSFException exception) { exception.printStackTrace(); } }
  • 63. despliegue sobre la JVM jgem install warbler jruby -S warble config jruby -S warble war WEB-INF y .war standard listos para deploy (perfecto en producción, poco ágil en desarrollo)
  • 64. despliegue sobre la JVM jgem install mongrel_rails #mongrel_rails start jgem install glassfish #glassfish_rails jgem install calavera-tomcat-rails #tomcat_rails permite cambios en caliente
  • 65. JRuby on Rails Ruby on Rails sobre la JVM javier ramírez http://aspgems.com http://spainrb.org/javier-ramirez obra publicada por javier ramirez como ‘Atribución-No Comercial-Licenciar Igual 2.5’ de Creative Commons