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
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.
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?
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
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)
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
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
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