Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | javier-ramirez |
View: | 3,121 times |
Download: | 1 times |
javier ramírez
http://spainrb.org/javier-ramirez
JRuby on Rails
Ruby on Rails sobre la JVM
http://aspgems.com
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
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.
Servlet API, Tomcat, Ant, Java API for XML Processing
qué
Ruby, el lenguaje
Rails, el framework
JRuby, la plataforma
self
http://aspgems.com
http://formatinternet.comhttp://javier.github.comhttp://spainrb.org/javier-ramirez
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...
Bancos, Administración Pública, Farmaceúticas, SGAE...
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
http://ruby-lang.org
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
ruby
foto con licencia creative commons por Javier Vidal Postigofuente: flickr
así que desde 1995...
¿Y cómo es que no supe nada de ruby hasta mucho más tarde?
1995 2002
Hipótesis de Sapir-Whorf: todos los pensamientos teóricos están basados en el lenguaje y están condicionados por él
¿por qué un nuevo lenguaje?
fuente: wikipedia
Hipótesis de Sapir-Whorf: todos los pensamientos teóricos están basados en el lenguaje y están condicionados por él
¿por qué un nuevo lenguaje?
Los diferentes lenguajes de programación, condicionan la forma en que los programadores desarrollan sus soluciones
fuente: the power and philosophy of rubyhttp://www.rubyist.net/~matz/slides/oscon2003/
Diseñado para ser divertido, creativo, y reducir el estrés del programador. Centrado en la resolución de problemas
¿por qué ruby?
fuente: the power and philosophy of rubyhttp://www.rubyist.net/~matz/slides/oscon2003/
Diseñado para ser divertido, creativo, y reducir el estrés del programador. Centrado en la resolución de problemas
¿por qué ruby?
Las personas son buenas en
•Creatividad•Imaginación•Resolución de problemas
Las personas no son buenas en
•hacer copias•trabajos rutinarios•cálculos, etc…
fuente: the power and philosophy of rubyhttp://www.rubyist.net/~matz/slides/oscon2003/
principio de la mínima sorpresa
principio de la brevedad (succinctness)
principio de la interfaz humana
enviar mensajes “ocultos” (syntactic sugar)
principios de diseño
fuente: the power and philosophy of rubyhttp://www.rubyist.net/~matz/slides/oscon2003/
ClassNames method_names and variable_names methods_asking_a_question? slightly_dangerous_methods! @instance_variables $global_variables SOME_CONSTANTS or OtherConstants
convenciones en ruby
fuente: 10 Things Every Java Programmer Should Know About Rubyhttp://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 objetolas 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 Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
nil es un objetonil.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 Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
dinámico
Reflection muy simpleClases AbiertasObjetos SingletonHooks integradosEvaluación dinámicaMensajes dinámicosObjectSpace
fuente: 10 Things Every Java Programmer Should Know About Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
dinámico. ejemplosdef create(klass, value) klass.new(value)endcreate(Greeting, "Hello")
fuente: 10 Things Every Java Programmer Should Know About Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
class Integer def even? (self % 2) == 0 endend3.even?=> false
class MyClass def MyClass.method_added(name) puts "Adding Method #{name}" end
def new_method # Yada yada yada endend
mensajes. method_missingclass 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 endend
fuente: 10 Things Every Java Programmer Should Know About Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
Proxies, Auto Loaders, Decorators, Mock Objects, Builders...
tiposfuertemente tipado, a diferencia de C y de igual forma que en JAVA
tipos asignados implícitamente y comprobados dinámicamente en tiempo de ejecución (late binding)
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 Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
class Duck def talk() puts "Quack" endendclass DuckLikeObject def talk() puts "Kwak" endendflock = [ Duck.new, DuckLikeObject.new ] flock.each do |d| d.talk end
tipos. algunas implicaciones
fuente: 10 Things Every Java Programmer Should Know About Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
def factorial(n) result = 1 (2..n).each do |i| result *= i end resultend
puts factorial(20)puts factorial(21)
243290200817664000051090942171709440000
public class Fact { static long factorial(long n) { long result = 1; for (long i=2; i<=n; i++) result *= i; return result; } public static void main (String args[]) { System.out.println(factorial(20)); System.out.println(factorial(21)); }}2432902008176640000-4249290049419214848
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 Rubyhttp://conferences.oreillynet.com/cs/os2005/view/e_sess/6708
domain specific languagesFeature: Hello
In order to have more friends
I want to say hello
Scenario: Personal greeting
Given my name is Aslak
When I greet David
Then he should hear Hi, David. I'm Aslak.
And I should remember David as a friend
And I should get David's phone number
fuente: http://github.com/aslakhellesoy/cucumber
class User < ActiveRecord::Base
has_one :address
belongs_to :company
has_many :items
validates_presence_of :name, :email
end
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
ControladoresVistas (+AJAX)ModelosPersistencia (validaciones)E-mailRESTRutasXMLTestingTareas
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
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 fixturesruby script/generate scaffold post title:string body:text published:boolean
rake db:migrate #ejecuta la migration y crea la tablaruby script/server #en http://localhost:3000/posts podemos ver la aplicación
rake #carga la base de datos de testing y ejecuta los tests
miniaplicación REST desde cero
prototipo generado
migration
modeloclass Post < ActiveRecord::Baseend
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
fixtures
funcionales
unitarios
deployment con rails
ServidoresApache/Nginx + passengerApache/Nginx + mongrel_cluster
basado en recetas escritas en ruby: capistrano, vlad, chef
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
IRBrubygemsYAMLZlibRailsActiveRecord-JDBCStringsRegExps eficientes
POSIXLibrerías Nativas (FFI)IO (ficheros, sockets, pipes...)RendimientoCompilación a ByteCodeTipos
fuente: Beyond Impossible, How Jruby evolved the Java Platformtalk by Charles Nutter at Community One 2009
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_CLOSEframe.packframe.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.Comparableend
button = javax.swing.JButton.new "Press me!"button.add_action_listener {|event| event.source.text = "YES!"}
java desde ruby
java es dinámico (si sabes cómo)
jsr 223 scripting APIimport 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 APIInvocable 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.rbdef say_wadus
“wadus”end
jakarta bsfimport 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
javier ramírez
http://spainrb.org/javier-ramirez
JRuby on Rails
Ruby on Rails sobre la JVM
http://aspgems.com
obra publicada por javier ramirez como ‘Atribución-No Comercial-Licenciar Igual 2.5’ de Creative Commons