format internet:

…please wait (49% completed)…

Los problemas del desarrollo web en España resumidos en senado.es

Posted by javier ramirez on November 12, 2012

disclaimer: he escrito este artículo después de navegar quince minutos por la web del Senado. No pretende ser un análisis exhaustivo de sus deficiencias. La mayor parte de los desastres que describo se corresponden a la sección de la web y del buscador (responsabilidad de VASS y GFI). La parte del pequeño Senado correspondiente a Ibermatica está algo mejor resuelta, aunque también presenta deficiencias.

Vaya por delante que 500,000 euros para una web compleja no me parece un precio excesivo. Pagar alrededor de 100,000 euros anuales por desarrollador es algo que entra dentro de lo normal, por lo que una web compleja que necesite de cinco desarrolladores durante un año va a estar en ese rango de precio. Si además la web incluye mantenimiento o necesita de cosas sofisticadas como gestión de documentos o un canal de streaming de video, el coste es normal que suba. Si la oferta también incluye los gastos de alojamiento y mantenimiento, me puede llegar a parecer incluso un precio bastante ajustado.

¿He dicho más de 100,000 euros por desarrollador al año? Sí. Exactamente. Es lo que cuesta contratar un buen servicio. Unos 50 euros la hora. De hecho, es bastante habitual encontrar precios por encima de ese rango, aunque también es habitual encontrar precios bastante más baratos. No conozco a ninguna consultora de las grandes en España que cobre ese dinero por sus desarrolladores, sino que el rango está más bien alrededor de los 20 euros (siempre se colocan perfiles de “más nivel” como jefes de proyecto o arquitectos que sí se venden por 50 euros la hora o incluso más caros, pero el grueso del equipo se factura a precio de saldo).

Cuando haces las cuentas, le quitas la seguridad social, el beneficio de la empresa, una pequeña reserva por trabajador para posibles indemnizaciones e imprevistos… nos queda que un desarrollador web que trabaje en una consultora, difícilmente va a poder cobrar más de 20000-25000 euros. Y si quiere ganar más, tendrá que dejar de desarrollar software y dedicarse a hacer tareas de gestión (arquitecto, jefe de equipo…) o comerciales (preventa, evangelista…). No hay nada malo en hacer tareas de gestión o comerciales, pero sí hay un problema en dejar que la gente que está construyendo tu software sea gente con poca experiencia o con una motivación baja. Por muy buenos jefes que tengas, si los desarrolladores no entienden el contexto de lo que están haciendo, el resultado va a ser subóptimo en el mejor de los casos, o desastroso como en el caso de la web del Senado.

El problema en España es que pensamos que cualquiera puede hacer una web. Como pintar una página HTML es lo más sencillo del mundo, tiramos a lo más barato y nos ahorramos un dinero pensando lo listos que somos. Y como no queremos pagar el dinero que vale, cuando la gente ya ha aprendido y tiene experiencia, se pasa a puestos de gestión donde van a poder ganar más dinero que le permita lujos tales como independizarse o incluso tener un hijo, con lo que los desarrollos los acaban haciendo siempre o la gente que acaba de terminar la universidad o los refugiados de otras carreras que se meten en la informática porque les dan un curso y con eso ya pueden hacer una web.

Hay más problemas que ese, por supuesto. Como el hecho de que para presentar una oferta a una administración pública te pidan unas condiciones imposibles de cumplir para cualquier PYME, o que a las grandes consultoras no les duela a veces hacer ofertas aún perdiendo dinero porque saben que ellas se lo pueden permitir.

El resultado de todo esto, es que las Administraciones públicas y las empresas grandes en España, con honrosas excepciones, tienen unas webs que dan vergüenza porque el desarrollo se lo han hecho estas empresas en las que la gente que realmente sabe está en puestos de gestión, y los pobres a los que les toca hacer el desarrollo hacen lo que pueden con los plazos imposibles que les piden, la poca experiencia que tienen, y las condiciones laborales de risa que les ofrecen.

Hablar es gratis, me diréis.. queremos pruebas.. no hay problema. Con la chapuza de web del Senado que se ha lanzado hoy veréis muy fácilmente de lo que os hablo. Independientemente de que el precio no me parece desorbitado, la web me parece desastrosa.

A simple vista, es una página web que funciona. El diseño no es ni mejor ni peor que el de muchas otras webs que hay por ahí. A mí personalmente se me antoja algo viejo para una web moderna, y el tamaño de letra me parece minúsculo, considerando especialmente que la web se autoproclama accesible, pero no soy experto en usabilidad así que no me quiero meter en esa guerra. En la guerra que sí me voy a meter es en la de las cosas que en un vistazo rápido están mal, aunque a simple vista un no profesional no se daría cuenta.

Cómo llegar hasta la página

Básicamente hay cuatro formas de llegar a una web. O le das a un enlace que alguien te ha pasado (facebook, twitter…), o escribes directamente la dirección de la web en tu browser, o la buscas en google (una gran parte de la gente siempre navega usando el buscador, no entienden que existe la barra de navegación del browser) o vas por un bookmark.

De esas cuatro opciones, TRES están rotas en este preciso momento. Si uno quiere escribir “senado.es” en su navegador, verá cómo le dice “página no encontrada” en lugar de mostrarle la home. Para poderla ver, es necesario escribir www.senado.es. Este problema es de primero de web, y es muy simple de resolver. Pero da una primera impresión de las prisas o la falta de cariño en este desarrollo.

Un problema mucho más grave. A día de hoy (aunque no por mucho tiempo) hay más de dos millones de páginas indexadas en google para el sitio del senado. Esto es bueno, de hecho es muy bueno. El problema es que esos dos millones son para la versión antigua de la web. En la versión nueva se ha cambiado el esquema de URLs, con lo que ahora todos los resultados que da google, excepto la home, han dejado de existir. Así como te lo cuento. El excelente trabajo de indexación de más de dos millones de páginas que YA existían en google, han desaparecido de la noche a la mañana porque a nadie se le ha ocurrido hacer un módulo que convierta de las URLs antiguas a las nuevas. Yo esto lo he programado antes en unos cuantos sitios y es un trabajo de unas pocas horas. El impacto es brutal.

Si alguien quiere probarlo es bien fácil. Ejecutas en google la búsqueda

site:senado.es

Y pinchas en cualquier resultado (excepto la home). Página no encontrada. Ajá.. bien. Por cierto, ya que hemos llegado a “página no encontrada”, intenta usar cualquiera de los enlaces del menú superior (cambio de idioma, contactar…) o del pie de página. ¿No puedes? Ya, ni yo. Otro detalle de primero de web que también se les ha pasado.

Obviamente si tenías un bookmark a la web, tampoco te va a funcionar por el mismo problema. Han cambiado las URLs, pero nadie se ha ocupado de redigirir las antiguas. Todo muy útil para la gente que, como yo, a veces se guarda enlaces a documentos para poderlos consultar más adelante sin buscarlos de nuevo.

Calidad del código de la página

Una vez llegamos a la página, lo primero que he hecho ha sido pasar el validador del w3c. Es una cosa que me gusta hacer siempre en las páginas porque me da una cierta medida de la calidad. Ojo, hay que tomarse los validadores como lo que son y no ser demasiado estrictos. Algunos problemas de validación son menos graves que otros y en algunos casos es imposible no tener algún error poco grave, como por ejemplo atributos extras.

En el caso de la web del senado, hay 88 errores y 44 avisos en la home. De esos errores unos cuantos son graves, como que hay input fields en zonas no permitidas (que puede hacer que algunos browsers no puedan usar los formularios) o que hay IDs duplicados (que puede complicar el desarrollo en el futuro, ya que cualquier desarrollador cuando programa una web espera que los IDs sean únicos, tal y como manda el estándar).

Si examinamos con más detalle el código fuente de la web, vemos que no se han tomado demasiadas precauciones para reducir el número de peticiones que hace la página, incluyendo al menos 12 ficheros en la cabecera. Cuando se programa un sitio en el que se espera mucho tráfico, esto debería estar mucho mejor resuelto. Además, si realmente va a haber mucho tráfico esperaría usar un CDN o cuando menos un dominio separado para los ficheros estáticos, de manera que no tenga que malgastar tráfico enviando las cookies para cada petición separada. Ya que estamos, utilizar varios subdominios estáticos me ayuda a enviar más peticiones en paralelo, haciendo que la página cargue más rápida.

Además, siguiendo con el código fuente de la página, en muchas de las páginas internas aparece javascript y css mezclado con el código HTML, lo que hace que las páginas ocupen más de lo que deberían (es decir, malgastan tráfico), hace que vayan más lentas y complica enormemente el mantenimiento en el futuro y la posibilidad de reusar código en otras partes de la web. Para ser justos, esta parte de código mezclado la he visto solo en el buscador, que es responsabilidad de GFI. Los desaguisados anteriores eran de la parte correspondiente a VASS.

Indexación en buscadores

Una parte importantísima del tráfico de un sitio llega por los buscadores. Cuando yo quiero informarme sobre algo, normalmente le pregunto a google, y luego sigo los enlaces. Me parece vital que una web en la que hay mucho contenido esté bien construída para que esos contenidos aparezcan indexados en Google/Bing y similares.

Ya hemos visto que el trabajo de indexación hecho hasta ahora con la web antigua se ha roto por completo con la nueva versión, pero ¿Está preparada para indexar bien los nuevos contenidos?

Para que una web indexe bien ha de tener estas consideraciones:

  • El código debe ser válido
  • Debe hacer buen uso de los elementos “title”, “description” y “h1”
  • La estructura ha de ser lo más semántica posible, añadiendo meta información extendida en los casos en los que se pueda (por ejemplo en el caso de las comparecencias, se puede añadir información del evento, o en el de los senadores información sobre la persona)
  • Los enlaces, las imágenes y los videos han de tener su “anchor text” o su “alt” bien definido pensando en los usuarios y, por tanto, en indexar bien
  • En un sitio multi idioma, hay que diferenciar a nivel de URL los diferentes idiomas y hay que proporcionar los enlaces canonical y alternate adecuados, para que cuando un usuario busca una página le aparezca en su buscador en el idioma más relevante para él
  • Si el sitio tiene mucho contenido, hay que proporcionar un fichero de sitemap en el que se le indica al buscador qué páginas lo componen
  • La estructura de las URLs debe ser clara

De todas estas consideraciones, la web del senado no cumple NI UNA SOLA. No solamente eso, sino que en su fichero robots.txt a día de hoy aparece una directiva en la que explícitamente se le pide a todos los buscadores que no indexen ninguna página del site, Ninguna en absoluto. Esto significa que cualquiera que busque información sobre el Senado en google va a encontrar cero referencias.

Móvil

En un mundo en el que la gente comparte enlaces via twitter/facebook/email y en el que cada vez más estos tres medios se leen en un móvil o en una tableta, me parece razonable pedir que al menos las páginas de aterrizaje estén optimizadas para estos dispositivos. No hablo de que el sitio completo sea usable por móvil, porque eso puede añadir un coste considerable, pero sí que las páginas susceptibles de ser enlazadas lo contemplen.

De hecho, Chus Pastor, la directora de Administración Pública de VASS, comentó que la web se vería en cualquier dispositivo.

Chus, ¿Has probado a verla en un móvil? Mírala tú, que a mí me da la risa.

Conclusión

Hacer una web es mucho más que saber escribir HTML y ponerle colores. Obviamente esas dos cosas son básicas, pero hay muchísimo más que has de tener en cuenta si tienes que hacerla, y aprender todo eso requiere tiempo y mucha experiencia.

¿Empezamos a ver por qué no es bueno que tu web la haga gente a la que le pagas poco dinero y, que por lo tanto, tiene poca experiencia? Ellos hacen lo mejor que saben, pero desafortunadamente no es suficiente para un sitio complejo.

Si quieres hacer una buena web, no solamente algo que “dé el pego” cuando la muestras en el browser, entonces necesitas gente que sepa lo que está haciendo. Y la informática tal cual se entiende en España provoca que esa gente abandone su carrera como desarrollador porque los sueldos y las condiciones son incompatibles con una vida digna.

Afortunadamente, hay vida más allá de las grandes consultoras donde el mundo es diferente y donde la gente se siente orgullosa de lo que hace. El reto ahora es que los grandes clientes se den cuenta de que les están timando y de que deberían exigir mucho más por su dinero. Y eso solo se conseguirá en la medida de que haya más sensibilidad hacia el trabajo de programador y más conocimiento de lo que aporta en un proyecto.

¿Son 500,000 euros muchos para hacer la web del Senado? No lo creo. Pero para el resultado obtenido, me parece un robo a mano armada.

Posted in development, internet, javier ramirez, SEO | Tagged: , , , , | 147 Comments »

Yo soy el programador perdido

Posted by javier ramirez on July 3, 2012

disclaimer for my international readers: this post is part of an ongoing conversation between different Spanish actors, so excuse my French ;)

Hay que ver la de trabajo que me dáis. Os da por escribir un par de posts, llega el otro y os reta a que lo debatáis, y a lo que me quiero dar cuenta me encuentro con que tengo que escribir un post para explicar dos cosas:

a) que en España hay gente capaz de liderar un proyecto con base informática tan buena como el que más
b) que es posible encontrarlos

Como me ha salido un post enorme, os pongo titulitos para que nos os perdáis. Que no se diga que no os cuido

¿ Es fácil encontrarme ?
=========================

Lo primero que he hecho al enterarme de que era tan difícil encontrar gente como yo, ha sido lógicamente preocuparme por mi SEO y me he ido a ver qué opina google.

Se ve que google me engaña. Las estadísticas de mi página personal en google webmaster tools dicen que en el último mes ha aparecido 2500 veces en resultados de búsqueda. La gente me
encuentra buscando cosas como “web development london”, “ruby uk”, “web developer london”, “ruby on rails developer” o “web developer uk”. Incluso alguien me ha encontrado buscando “bachata logo”. Los caminos de google a veces son inescrutables, pero parece que si alguien quiere encontrar un desarrollador web/ruby en Londres, lo tiene fácil para encontrarme. Antes de mudarme aquí, vivía en Madrid y los resultados de google eran equivalentes, pero para el mercado español.

Mi página personal está, como buena cuchara de palo en casa del herrero, muy descuidada, siendo mi presencia online mucho mayor en mi twitter, mi blog, las presentaciones que tengo colgadas en slideshare, mi canal de vimeo, o mi repositorio de (escaso) código en github. Se diría que no soy tan difícil de encontrar.

Y si lo tuyo no es internet, sino que es el mundo más físico, en el último año he dado charlas en tres o cuatro eventos, y he participado como público en varios otros. En Madrid, en Londres y en otras ciudades. Algunas de estas charlas eran internacionales, en inglés. Se ve que a pesar de ser español hay gente de otros países que piensa que puedo aportarles cosas a ellos que son de países tan avanzados con sus hordas de programadores talentosos.

Al parecer hay más gente como yo porque en ASPgems, de la que soy CTO, cada vez que hemos necesitado incorporar gente al equipo, hemos tenido la suerte de encontrarla en muy poquitos días. De hecho por lo general apenas necesitamos descartar gente en entrevistas porque al parecer atraemos al tipo de gente que nos interesa y tenemos suficientes referencias de los candidatos como para no tener que andar perdiendo el tiempo en test psicotécnicos o en preguntar cuál es su mayor virtud.

Pero, ¿soy tan bueno como los programadores de USA o UK?
=========================================================

Habiendo quedado medio claro que los programadores no nos escondemos mucho y que alguien con un cierto interés lo tiene fácil para encontrarnos, parecería que afortunadamente el problema no es que yo no exista, sino que quien me busca quizás ande más perdido que el programador del título del post que lo empezó todo.

Ahora contaré posibles sitios donde buscar gente más allá de los tópicos, pero antes dejadme que cuente así rápido por qué creo que soy el programador perdido del que hablaba Enrique Dans y por qué sí creo que esa rara avis existe en España.

Tengo algunas pruebas que confirman que soy al menos tan bueno como los programadores que hay en Estados Unidos o Reino Unido (los dos países mencionados en el mensaje original)

a) frecuentemente recibo ofertas de esos dos países para incorporarme a sus equipos.Algunas de las ofertas vienen de recruiters que, angelicos, no saben ni por dónde les da el aire y que contratarían a Wally  solo por llevarse la comisión. Pero muchas otras ofertas son de gente que me conoce directamente o por referencia y que están interesados en contratarme a mí, un programador español que no existe en un mundo lleno de peligros, para su empresa.
b) gente con la que he trabajado o a la que he tenido cerca está felizmente trabajando para empresas de esas que molan como github, google, microsoft, paypal, heroku, o engine yard
c) he vivido en Nueva York y en Londres y veo lo que se mueve. Complejos cero

¿Qué hay que hacer para conseguir contratarme?
==========================================

Antes de que te cuente cómo puedes contratarme a mí o a otra gente como yo, asegúrate de estar seguro de lo que deseas. Como en todas las profesiones creativas (y aquí incluyo al equipo de ventas) trabajar con un profesional puede ser muy divertido, inspirador a veces; pero estresante y frustrante si es tu primera vez.

El artículo de @edans dice “En España, las personas de verdad capaces de convertirse en el alma de un proyecto y transformar su esencia e ideas en código, esos participantes esenciales a los que se entregan acciones para asegurar que permanecen en él, prácticamente no existen

Si voy a ser el alma de tu proyecto, convierto su esencia en código y me consideras un participiante esencial, olvídate de cosas como “el que paga manda”, “el cliente siempre tiene la razón” o “esto me lo hacen en patolandia por la mitad de precio”.

Si trabajas conmigo, prepárate para que te diga mil veces que estás equivocado, para que te rebata todas las cosas con las que no esté de acuerdo, para aceptar que algunas cosas simplemente “son así”, para que cometa errores y no pase nada porque al fin y al cabo lanzar un proyecto es lo que tiene, para que los resultados no sean exactamente como esperabas pero se le parezcan, y para muchas otras cosas a las que probablemente no estés acostumbrado.

A cambio, la flexibilidad funcionará en los dos sentidos: renunciaré a veces a la mejor solución técnica porque es importante salir en una fecha determinada o porque resulta que es super importante cambiar algo porque hay un inversor/partner que se ha encaprichado con eso, me preocuparé de cómo va tu analítica y de si los usuarios tienen algún problema usando el site, y te daré herramientas para que puedas desarrollar el área de negocio tanto como sea posible. No pasa nada, ya hemos jugado antes a esto y sabemos de qué va. No hace falta que me cuentes lo difícil que es tener una empresa; yo ya voy por mi segunda.

Si acepto estar en tu proyecto, el proyecto pasa a ser nuestro. Y me da igual que yo sea contratado, subcontratado, socio, freelance, contribuidor desinteresado en un proyecto open source o cualquier modalidad que se te ocurra. Si decido dedicar mi tiempo y mi esfuerzo a un proyecto, ese proyecto pasa a ser también mío. No estoy hablando en términos económicos, sino en términos de “compromiso emocional”. Si no me dejas que me sienta parte del proyecto, no creo que me quede mucho tiempo alrededor.

Ah, y búscame amiguitos que sean tan buenos como yo.. a ver si vas a pretender que sea el único que sabe y me apañe con cinco becarios encontrados por infojobs. A la gente buena le gusta rodearse de gente buena. Y le gusta tener su tiempo para sus cosas y compartir lo que sabe y aprender de otros y muchas otras cosas que ya te irás dando cuenta.. mantén una mentalidad abierta.

¿sigues queriendo encontrarme? perfecto.. te cuento cómo

Sí, quiero. ¿Dónde te encuentro? 
==========================

Estoy trabajando, gracias. ¿No te pensarás que un programador así tiene problemas para encontrar un buen trabajo, no? Entonces.. ¿qué haces buscando en infojobs? Es posible que ocasionalmente haya alguien bueno trabajando listado ahí (con un cv de los años 80), pero yo a día de hoy no conozco a nadie que encaje en la definición de buen programador que esté desempleado en contra de su voluntad. Ha pasado mucho desde el crash de las punto com; esto no es 2001 y nadie se acuerda de Terra o Teknoland. Infojobs no te va a ayudar a buscar el profesional que necesitas.

Hay gente buena trabajando en infinidad de sitios. Leyendo los comentarios de la gente que responde a estos posts parecería que solo hay vida inteligente en las empresas pequeñas, los freelances o las startups con nombres de dominio super guapos. Es verdad, en algunos de esos sitios hay gente buena (y gente apestosa, como en todas partes). Sin ir más lejos conozco gente excepcional en empresas tan denostadas como Indra. Yo mismo antes de montar mi antigua empresa, abandonarla e irme a mi empresa actual, pasé algún tiempo trabajando en empresas de servicios en las que hay gente tan buena como en cualquier otra.

Lo que pasa es que esa gente ya no está trabajando de programador porque no les dejan. Están en puestos de preventa, I+D, jefes de proyecto, arquitecto software, evangelizador, developer advocate.. lo que pone en la tarjeta es distinto, pero la pasión por un buen reto es la misma. No dejes que los prejuicios te hagan creer que no hay gente buena en las empresas grandes. Solo es que están más escondidos detrás de sus corbatas ;)

Entiendo que, a no ser que tengas contactos, es difícil ir empresa por empresa y buscar a la gente buena. Tengo buenas noticias para ti. A la gente buena le gusta estar al día. A algunos de ellos incluso les gusta relacionarse con otra gente de vez en cuando (a otros les gustaría, pero tienen menos tiempo). Los sitios más obvios para encontrar gente a la que le gusta su trabajo son las listas, grupos y foros de internet. Lo bonito de esto, es que TODOS los grupos y listas de correo aparecen en google. Solamente necesitas saber lo que buscas.

Si necesitas hacer un proyecto web, las tecnologías más habituales a día de hoy son Ruby on Rails, Javascript, PHP/Drupal y Python/Django. Hay otras tecnologías, pero en una startup moderna lo más probable es que tu proyecto sea en Ruby on Rails o PHP y siempre con parte de JavaScript. Ahora vete a google y busca la lista de correo de esa tecnología en tu país. O mejor todavía, busca el grupo de gente que se junta en tu ciudad. Vete a google y busca “Grupo de Ruby on Rails en Madrid”. Envía un correo a la lista o acude a la siguiente reunión y cuéntales tu problema. Si la tecnología no es la más adecuada seguramente puedan orientarte hacia otra mejor.

Solo ten en cuenta que estás hablando con gente inteligente y que no les va a gustar si mandas mails del tipo “empresa multinacional líder busca…” o “proyecto super secreto que solo te contaré tras firmar un NDA”. Esos mails van al mismo sitio al que van los de “compre v1agra” o “cambia tu contraseña de paypa1”. Y sigue la famosa norma de no vestirte ni mejor ni peor que tu público. Si vas a una reunión de gente que va en camiseta, no vayas con gemelos o será más difícil que se te acerquen. ¿O acaso te pensabas que los prejuicios son siempre de la gente con traje a la que va vestida de perroflauta? :p

Si aún así no encuentras al programador que buscas, ponte en contacto conmigo que te digo yo dónde lo puedes buscar.

Y si en vez de un programador, lo que quieres es una empresa que sea tu socio tecnológico y te lleve el desarrollo, mándale un mail a nuestro CEO (el señor grande que salía hablando en el debate10), que estará encantado de echarte una mano.. y yo también.

Posted in aspgems, debate10, development, internet, javier ramirez, off topic | 61 Comments »

Trying out Rails 3.1

Posted by javier ramirez on June 30, 2011

Rails 3.1 is almost here, and all the rock star ninja hipster early adopters have been playing with it for a while. I’m not a ninja (picture me with a black tight skin suit if you wonder why), so I didn’t install it until today.

Installation is pretty straight forward, but there are a couple of tricks, so here they are in full Technicolor to save you a couple of minutes.

The first thing you are going to need is the right gem, which you can install directly via

gem install rails --pre

I didn’t want to install it as a system-wide gem, so I created a new gemset in rvm like this

rvm gemset create r31

If you are on windows and don’t have rvm, maybe you could install another version of ruby via pik, but I cannot help you with that.

Anyway, system-wide or scoped to a local gemset, after installing the gem you should be able to create your first rails 3.1 project like this

rails new sandbox

If you are on rvm, don’t forget to create a .rvmrc file with your local gemset to make things more convenient. In my case the contents of the file are

rvm 1.9.2@r31

Are we there already? not yet! Rails 3.1 needs a javascript runtime for all the asset magic. You can choose the runtime of your choice, as long as your choice is one of the options here :p

I chose (see update below!) the rubyracer because I’ve heard good things about it lately, but what do I know, just pick the one you prefer and add it to your gemfile. In my case it looks like this

gem 'therubyracer'

And, you know, now you need to bundle it

bundle install --binstubs

And that’s it, now you can do things like

bin/rake -T

Of course you can start the rails server too

bin/rails server

You know the rest of the song.. Now go to http://localhost:3000 and start dancing!


update:
i found some errors when using ruby 1.9.2p0, therubyracer and coffescript. I changed to nodejs (just install it and leave the binary somewhere in your path) and things got back to normal

Posted in development, javier ramirez, ruby, ruby on rails | Tagged: , , | 3 Comments »

How we improved FACTURAgem security, or how to set HTTPS for your rails application

Posted by javier ramirez on March 31, 2011

As you probably know, one of the products in my company is FACTURAgem, a web application for making simple invoices targetted to those users who are currently invoicing using word, excel or a notepad and a ballpoint.

Since your invoices are something you don’t want to share with the rest of the word, all the pages protected by login were securily encrypted and served via https since the first day, and the session cookie was automatically expired when the browser is closed, so the system was pretty safe.

Still, there was a very small chance of someone hijacking your session, if you were using FACTURAgem and you happened to be sharing a public network with a hacker nearby who was interested in accessing your FACTURAgem account. Due to the profile of both our users and our application this scenario was not likely to happen, and we never had any security breach since we launched the product.

However, with the proliferation of public networks and the quick adoption of smartphones, ipads, netbooks and a myriad of always-connected portable devices, we wanted to add an extra layer of security for our users, so now they can safely use FACTURAgem at any place without any worries.

Since yesterday, all the pages in FACTURAgem, both private and public, are securily served via https. Even if you forget to include the “s” when accesing the apllication, our servers will redirect appropriately to the safest version.

For the technically savvy, I will explain the highlights of the process:

note: FACTURAgem is running on an Apache/Passenger/Rails stack. If you are using a different setup, details might be differ, but the spirit is the same.

We had to cover different fronts of the https problem:

Configuring a certificate and SSL virtual host for Apache.

This was already done in our case since the beginning of the project. There’s a lot of information out there about how to do this.

Telling Apache to redirect all the traffic to https

We had to instruct our non-ssl virtual host to redirect all the traffic to the SSL one, so if you type http://www.facturagem.com/help you should be redirected to https://www.facturagem.com/help instead.

This is easily done with:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Unfortunately, in our case, we had an extra constraint. There are a couple of subdirectories we don’t want to put under SSL, because they are served by an external service that cannot run under https. For those pages, we will not store any session information, so they will not be a security problem. All we had to do is telling Apache not to redirect if the url is in one of those directories

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !.(fictional_directory_name|another_fictional_directory_name).*
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

By doing this, if you try to visit http://www.facturagem.com/fictional_directory_name/whatever you will not be redirected to https.

Making sure we marked the cookie as secure, so we are 100% sure it will never be passed to non-encrypted pages

By setting a cookie as “secure” your browser is smart enough to send the cookie back only when asking for a SSL resource. That way, even if you are browsing unsafe pages from the same domain, the cookie will not be transmitted, so your session is not subject to attacks.

If you are setting your cookies “manually”, secure is one of the attributes you can set. But if you are using session cookies in Rails, it’s as easy as setting an extra parameter when configuring your session cookie.

ActionController::Base.session = {
:key => '_your_application_secure_session_id',
:secret => '11111222312321321321321313213213213213213213213237761223213213213213131231231321321312',
:secure => Facturagem.config.secure_cookie
}

Some things to consider here. If you are changing a live application, as it was our case, it’s a good idea to change the name of the cookie. That way, you are sure everybody is going to be using the secure version. Otherwise, users with a valid cookie would still use the non-secure version in some browsers. By changing the name, you are sure everyone is setting a new cookie and everyone is secure using your site. The collateral effect is you will be signing out all of the users browsing your site, so take it into account.

Also, note how we are using a config variable to set a secure cookie (or not). This way, our developers can work without locally enabling SSL.

Removing any references to http external resources, so we avoid the “mixed content” message in some browsers

By this point everything should be working fine, but if you are using any resources directly by absolute URL (as is the case of external js or, in many ocassions, images referenced from your stylesheets), then you will be having the “mixed content” message and your users will feel something is not right.

Your first impulse can be changing all the “http://” ocurrences in your files for “https://”. That would fix the problem on production, but should any developer work without SSL, she would experience the mixed content alerts.

There is a not-so-known-but-perfectly-fine solution for this. You can use relative network-path references , also known as protocol relative urls. To make a long story short, if you write ‘//www.google.com/jsapi’ it will use http or https depending on which protocol you are using on the current page. That way, you can forget about which schema you are on. There’s a caveat with explorer downloading twice the javascript files (at least until IE8 there was), and if you want more info Paul Irish has it ready for you.

That was it! by following those steps we were able to make our site more secure and it took just some hours to set up. Now you can use FACTURAgem when you need to, without worrying who your neighbours are.

If you are out of Spain, pay attention to @facturagem, because we are going to be launching an international version pretty soon.

Posted in aspgems, development, javier ramirez, madrid, ruby on rails | 2 Comments »

Installing a Rails plugin from a github branch

Posted by javier ramirez on October 13, 2010

Today I wanted to install a plugin from github into a rails project. So far so good, you would think. You only need to run script/plugin install and start coding right away.

Unfortunately, the branch of the plugin I need is not the master one, because this applications runs on rails 2.3.x and the master branch has been adapted to rails 3 already.

I could just download the tar file from github, or I could make a git clone and checkout the branch I wanted.. but it turns out I don’t need to do any of those, because old good script/plugin has an option to checkout a specific branch

script/plugin install http://github.com/rails/exception_notification.git -r 2-3-stable

And I can start coding right away.. and that’s exactly what I’m going to do after publishing this post.

Posted in development, javier ramirez, madrid, ruby on rails | Tagged: , , , , | 7 Comments »

Happy 4th birthday ASPgems

Posted by javier ramirez on June 6, 2010

Four years ago I thought I was at the top of my career. The company I had co-founded was starting to look much like a nine to five job and I decided to resign and accept a great position as a post-sales engineer in FatWire, where I would have the chance to improve their content server solution, which in my opinion was the best of the market by then. Things were looking sweet: new challenges, smart jobmates, important clients, interesting salary… and then I got an IM from Ana Isabel that changed it all (you gotta love it was not a phone call, mind you)

She told me about this brand new tiny company she was starting up together with Agustin Cuenca and some other folks I didn’t know by then, and who resulted to be brilliant. The idea was to be an Application Server Provider and offer products in the later so-called cloud to help small and medium size companies manage their businesses. They would also develop web applications for third parties. And they would do it all using this new toy called Rails, after a successful proof of concept for a real client by Xavier Noria. Regarding project management, they didn’t want to use a traditional approach, but going down the Agile road and use Scrum. The name of the company was ASPgems, where ASP stands for Application Server Provider and “gems” was something related to this Rails thing.

I was very reluctant to join them. Apart from having just landed into a great job position, I had a lot of doubts about the new company. They didn’t have any money, so I would have to cut down my salary and trust the company would eventually make it; they were working remotely, so I thought nothing would get really done; they didn’t have any big clients, and I came from the banking/public sector/corporate world; and to top it all they were using this Ruby on Rails framework and these requirementless agile methodologies.

My first experience with Ruby, some years before, was painful. I had to make some kind of automatic web crawler and I found libraries for doing it both with Ruby and Jython. I didn’t knew any of them so I tried them both. Right now I don’t remember why I didn’t choose the Jython library, but I know why I didn’t choose Ruby. After half a day trying, it was impossible to make the thing work on my windows machine, and all the documentation was in Japanese, so good luck with it. I finally coded my own crawling solution in good old Java and XML.

So you can imagine I was skeptical about Ruby. Then I started to read about Ruby and Rails and I panicked: no static type check, lack of hosting options, poor windows support, opinionated instead of configurable, with a certain disdain for the database layer… my Java instincts were alerting me with a lot of red signals. And then I made “the mistake” of having lunch with Ana and Agustin. They were really excited about the company, they saw a world full of possibilities, and the sense of adventure was just too strong for me to resist. Besides Agustin had been the guy who started Qarana, the best company I had worked for until then. It was just natural for me to join ASPgems.

By adopting Rails as her development framework, ASPgems was making a statement: We don’t care what other people are doing, we want to use the best tools available with or without the support of the rest of the industry. Living up to that statement takes a lot of work. First you have to be sure you are using the best tools available, so you have to be scanning the surroundings all the time to see when it’s time to move to the new best thing. Besides, you have to keep up to date on all the changes and on the new libraries available. And of course in many occasions you will have to be the one building those libraries, because getting there first means no one did the work for you yet. This living on the edge thing can be really time consuming, but things get much easier when you find a friendly community sharing your passion. And in Ruby/Rails we are really lucky on that issue.

Today is ASPgems’ fourth birthday and I’ve been a part of the company almost from the first month. If I have to judge in terms of personal development, I can say without any doubts this is the best company I’ve worked for, and I guess that’s why I’ve stayed here longer than in any other place before.

Below are some of the things I have done in the last four years. Had I stayed in my safe Java corporate world, I’m not sure I wouldn’t have done some of these things, but I’m sure ASPgems inspired me to do most of them.

I have..

..attended more conferences (and camps, and other events) in the last four years than in the previous 10+ since I started working on IT.
..organized and presented talks in both national and international conferences
..co-started a local ruby group
..curated an extensive online presence: blog, personal page, vimeo, slideshare, mailing lists, communities…
..greatly improved my google ranking, making my conventional CV irrelevant
..written a book

..learnt how to better manage web projects
..seen clients really happy to see their projects going live on time
..shared my knowledge with both clients and competition
..launched more web applications than I can remember

..taught ruby on rails
..introduced some friends to the Ruby on Rails/Agile world
..developed a taste for being an early adopter on new technologies
..adopted ruby on rails for my personal and freelance projects
..switched to linux
..bought several domains and rented my own VPS

..learnt about SEO and Analytics
..made websites scale, and learnt a lot during the process
..learnt a lot about IT (web servers, process monitoring, system set up and configuration…)
..improved vastly my skills on client-side web developent
..been wrong many times, and happy to learn from those mistakes

..helped to build one of the most solid development teams I have seen
..worked together with the commercial department, and not against it

..kept in contact with brilliant developers from all over the world
..started repositories in github and rubyforge
..collaborated in several open source projects

..realized money is just a secondary motivation

Happy birthday ASPgems, and thank you.

p.s. By the way, remember how skeptical I was about Ruby? I was wrong, and happy to be. Go try it by yourself!

Posted in aspgems, javier ramirez, madrid | Tagged: , , , | 7 Comments »

SEO for developers

Posted by javier ramirez on March 10, 2010

As a web developer, my work involves much more than just coding; many times I find myself covering topics such as user experience, scalability, reliability of the system, or metrics and analytics to track the acceptance of a site.

SEO is left many times on the hands of the marketing team, but there are many technical aspects that are important in order to make a site appealing both for visitors and searchbots. Since web technologies (and search engines) evolve quickly, if you want to have a good site you need to keep posted about the latest developments. Sadly, there are a lots of materials based on outdated information and there are many myths and legends around the topic

I have been following closely the status of web crawling and indexing for some years, and we have been applying with success many of the practices I’ve learned to improve the sites of some clients. None of these practices involved links from external sites or bought traffic, just a better structure and changes of the contents and the sites’ internals.

Since we want to follow these practices in all the projects we are taking, I decided to prepare an internal training session for the ASPgems’ development team.

Here are the slides for my presentation. Even if they are not as good without the explanation (sorry, no video this time), I hope you’ll find them useful. UPDATE: video -in Spanish- has been uploaded to the media page of my blog.

This material is published under a Creative Commons NonCommercial-Attribution-ShareAlike license 2.5

If you find it interesting or if you are going to use it for any purposes, I’d appreciate an e-mail to jramirez@formatinternet.com

Posted in development, internet, javier ramirez, SEO, sites | Tagged: , , , , , | 10 Comments »

Slides and video for my talk “La herramienta de desarrollo definitiva” in conferencia rails 2009

Posted by javier ramirez on February 28, 2010

I just realized I still hadn’t published in my blog the slides and video of my talk “La herramienta de desarrollo definitiva” in conferencia rails 2009, back in november.

My talk was a reflection about web development and the relative importance of the development tools. I was defending the idea of the individual with good practices being much more important than the choice of a tool or another. I was also talking about why Ruby on Rails is very appealing for such an individual and why it’s still relatively hard to find companies using modern techniques in development.

I talked about which were the best practices I consider an “ultimate developer” should embrace, linking it to concepts found in geek literature such as The Mythical Man Month, The Cluetrain Manifesto, Microserfs o The Soul of a New Machine.

This material is published under a Creative Commons NonCommercial-Attribution-ShareAlike license 2.5



The video is divided in two parts:

Vodpod videos no longer available.

Vodpod videos no longer available.

Posted in conferences, conferenciarails, conferenciarails2009, javier ramirez, ruby, ruby on rails | Tagged: , , , , , | 3 Comments »

IE cache for Ajax requests

Posted by javier ramirez on January 14, 2010

A few days ago I ran into an issue that is now obvious but took me a while to figure out. I was programming a chat client and everything was working fine in Firefox and Chrome, but when I tested it on IE (6 and 8) things were not looking so good.

This chat is following the polling pattern, issuing an Ajax call every three seconds to check for any updates and receiving a JSON array with the pending messages, if any. Using prototype.js the code to call the javascript function every three seconds is this

new PeriodicalExecuter(Aspchat.chatRemotePoll, 3);

On IE the chat was initialized properly, the first call to the remote server was working fine, but the periodical poller was not issuing any further calls. At first I thought the problem was on PeriodicalExecuter, but after a bit of debugging I could see “Aspchat.chatRemotePoll” was being called, but the Ajax call inside was apparently ignored.

To make things more interesting, I could see some other Ajax requests were working fine (for example, the one to send messages or to update the user list).

Comparing the requests that were successfully sent with the ones that were ignored, I could see the difference. In the working requests I was using POST (the default when using prototype) but in the ignored calls I was using GET.

Once I saw this, it was easy to diagnose what the problem was. IE was caching the GET requests, even when using AJAX. To be honest, this time I will not even blame IE, since I understand a GET request is subject to cache. In this case, I would even say I prefer the IE behaviour over that of Firefox and Chrome.

There are basically three things you can do to prevent this kind of behaviour:

  • The easy way out would be to convert my GET request to a POST one. Alas, I didn’t want to do it because in this case I was being RESTful and I was using the same URL for two different actions. When calling “/aspchat/messages” via GET I’m asking for new messages, but when calling via POST I’m sending a new message to the channel.
  • Set HTTP headers to control client cache
  • Make the request unique by adding a timestamp (or similar) to the URL

The solution I like the best is the one with HTTP headers, so I just went to my poller action (which by the way is managed via a Rails metal middleware) and added the Cache-Control: no-cache header. Just to be really sure, I also added the timestamp for extra security.

The prototype for the Ajax call with the timestamp looks like this

new Ajax.Request('/aspchat/messages', {
           parameters: {timestamp:new Date().getTime()}, //we need this to avoid IE caching of the AJAX get
           method: 'get',
           onSuccess: function(transport){
               Aspchat.displayChatMessages(eval(transport.responseText));  //pass the JSON array to displayChatMessages
                         }
       });

As an extra ball, you can see how I’m using the onSuccess callback to interpret the JSON I’m receiving from the server.

Now you cannot say you didn’t know your AJAX requests could be cached. Let’s be careful out there.

Posted in 1771, development, internet, javier ramirez, ruby on rails | Tagged: , , , , , | 15 Comments »

Eclipse buttons not working on Ubuntu Karmic Koala

Posted by javier ramirez on December 23, 2009

Lately I was experiencing a strange behavior when working with Eclipse/RadRails. Some of the buttons didn’t work anymore. I could click on them, but they’d just appear as selected, without performing any actions. I had to use the enter key to actually click on the button.

Since I had run an update some days ago, I was blaming some new version of one of the installed plugins.. but I was wrong.

Today I read this post where it explains how to fix it. It’s a conflict between Eclipse and the latest versions of GTK+. By setting the GDK_NATIVE_WINDOWS variable to use native windows, everything is back to normal.

And they lived happily ever after (or until the next major release anyway)

Posted in development, eclipse, javier ramirez, madrid, ruby, ubuntu | 5 Comments »