format internet:

…please wait (48% completed)…

Archive for the ‘ruby on rails’ Category

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.

Advertisement

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

Multiple rubygems versions, GEM_HOME and GEM_PATH

Posted by javier ramirez on September 28, 2009

Installing rubygems is failrly easy and it’s great to have a package manager so you can forget about manually installing and upgrading the components you use. After installing a gem, you can require it from any ruby script and use it hassle-free. Well, given your ruby interpreter can find it.

When you install rubygems, a lot of default configuration is done behind the scenes. If you must see to believe, you can run

gem environment

do you believe me now?

Unless you are on windows, you have probably experienced already that gems can get installed in different locations. If using a superuser account, the global configuration will be used, but with a regular account gems install under your home directory.

If you are not careful about how you install your gems, or if you are using rake gems:install from regular accounts, you might end up installing the same version of a gem twice. That’s not only WET (not DRY, bear with me here) but it eats up your poor HD.

Things can get a lot worse than that. Suppose you are working with both JRuby and Ruby MRI. When you use rubygems from JRuby, it will try to use a different gem location by default. So, depending on how you are installing gems, you could have up to three different copies of exactly the same version.

And if you are on ubuntu and you upgrade from an old version of rubygems to the latest one —you will have to if you install Rails 2.3.4; if you are having problems you can read right here how to update it— you might be surprised that your gems are being installed *again*. The reason is under older versions the default location was “/var/lib/gems” and the latest one defaults to “/usr/lib/ruby/gems”.

Well, four different copies of ActiveRecord 2.3.4 are three and a half more copies than I wanted, mind you.

So.. how can we stop this gem install frenzy? Easy. Don’t use the defaults. Each of your installations is using default values, but they can be easily overridden with command line parameters or much more conveniently with environment variables.

Remember the title of this post? Can you see anything there that would make a good candidate for environment variables? That’s right, all the rubygems versions honor the GEM_HOME and GEM_PATH variables, so if they are set they will be used.

Depending on your OS, you can set these variables in different places. I’m on ubuntu and a bit lazy, so I chose the easiest, which is by adding this to my .bashrc file.

export GEM_HOME=/var/lib/gems/1.8
export GEM_PATH=/var/lib/gems/1.8

And now, no matter what I’m using: Ruby MRI, JRuby, or the latest rubygems, my already installed gems will be used, and the new ones will be put in the same place.

Saving the world is a hard job, but someone has to do it.

Posted in 1771, development, jruby, ruby, ruby, ruby on rails, ruby on rails | Tagged: , , , , , , | 7 Comments »

Video of my talk “Jruby On Rails” at the Sun Open Communities Forum

Posted by javier ramirez on August 23, 2009

I just knew the video of my talk about JRuby on Rails at the Sun Open communities Forum is already online. Funny how a google alert let me know this video has been published even before the official web page of the event was updated.

The talk is in Spanish and the slides I used are available at slideshare.

If you are a Java developer interested in JRuby and you are going to be in Madrid in September, stay tuned because it’s very likely I will be speaking again about JRuby in SIMO

Posted in conferences, jruby, ruby, ruby on rails | 4 Comments »

My slides for “Jruby on Rails: Ruby on Rails sobre la JVM”

Posted by javier ramirez on June 25, 2009

It was interesting to be at the Sun Open Communities Forum and meet people I used to work with (or even teach to) as back in time as in 1996.

It was also interesting to have the opportunity to introduce Ruby and Ruby on Rails to Java developers and show them how they could use it from the familiar JVM.

As usual, I uploaded to slideshare the slides I used in my presentation.

The layout might be a bit enterprisey for my standards, but I was representing my company, so I used the company template. Anyway, the presentation is under Creative Commons, so feel free to use it in any way you can imagine, as long as you respect the “non commercial attribution share alike” license.

Posted in conferences, development, javier ramirez, jruby, madrid, ruby, ruby on rails | Tagged: , , | Leave a Comment »

Cucumber, Selenium, Webrat, and Windows

Posted by javier ramirez on April 27, 2009

I spent last Saturday hacking around with some really smart people in Madrid. It’s not widely known than in Spain there’s a thriving Ruby on Rails community -my guess would be a language thing- but if you take a look at some of the Rails patches, Hackfest winners or the official Rails documentation project, you would be surprised to see how many -and how good- contributions are coming from this side of the world.

Once in a while we like to get together and take code challenges, so we can learn from each other and eat pizza to match the stereotype ;)

Thing is I’m a Windows guy. I know I should be sorry, I know it’s for housewives (or househusbands for that matter), but that’s life. (disclaimer: I’m planning to switch to Ubuntu in the near future)

As you know, developing software in windows while entirely possible is a bit more difficult than in other systems, specially when it comes to compiling, forking and the like.

Last Saturday I was, as usual, the only windows at hand (the rest being a lot of Macs in different flavors and a lonely Ubuntu) and, as a part of the code challenge, I had to run some tests with Cucumber, Selenium and Webrat. Apart from libxml, that has been working flawlessly in my computer for months, no other binaries were involved, so you would think everything was working just fine.. well, think twice.

First problem was the test server couldn’t be started automatically. I didn’t investigate much about it (my guess being that a fork or a system call is being issued and Windows cannot cope with it) since it was easier just to start it manually before running the tests. Also it was faster, because it didn’t need to be started every time.

After this obstacle, when I was trying to run the tests, I was getting a cryptic Errno::EADDRNOTAVAIL message. At first I thought it was because of Selenium not being able to bind to the given port, but a quick test from the command line discarded that possibility.

I don’t know anything about webrat (yet) but as the song goes, with a little help from my friends I was able to locate the source of the problem. When connecting to remote control Selenium, Webrat is trying to bind to the address “0.0.0.0” and that’s something Windows doesn’t like.

All I had to do was opening the file “selecium_rc_server.rb” at the gem source and replacing “0.0.0.0” by “127.0.0.1”.

I was told I can do this much more clearly at the Webrat config, but I tried it out and I still had the same problem. Taking a look at the Webrat code I would say the config param is not honoured system-wide, but truth is I was in a hurry and I didn’t researched it thoroughly. I had a challenge to solve after all ;)

Once I did this, all was hunky dory. Selenium started, the form fields were filled in, the tests were passing (or not) and the result was displayed on my not-ansi console. Bummer.

Believe me, cucumber is not half the fun without the colors in the output. Fortunately enough, google can tell you where to find lots of ansi-aware console replacements. Unfortunately enough console2, my favourite, is not one of those.

So, there, it took a bit of extra work but now you can also run this neat stack in your good-old windows box.

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

Speaking at EuRuKo 2009

Posted by javier ramirez on April 23, 2009

It’s only two weeks for EuRuKo 2009, the most important Ruby conference in Europe.

As you probably know, EuRuKo is a grassroots itinerant conference, entirely organized by -and for- Ruby developers. This year, the conference will be held in Barcelona, and I have the honor of being a -tiny- part of the organization as a member of the Spanish Ruby Users Group, the local group preparing the event.

It’s also pretty cool that ASPgems is one of the sponsors. I cannot help but feel a tang of pride (awww, the diva in me ;) ) when I see the commitment and support of the company when it comes to community events.

The list of scheduled talks looks promising. Starting with Matz’s keynote there will be sessions about things like cross-platform mobile development, voice-enabled applications, interacting with MIDI instruments from Ruby, Image processing and other non-typical uses of Ruby. They have the sweet scent of EPIC WIN all over.

Did you take a look at the list of talks? Any familiar names? Well.. yours truly’s talk proposal was accepted and I’ll be speaking about game development using Ruby and Gosu. How cool is that?

I’ve been speaking at other technical events before, and I have a good deal of experience in training, but this will be the first time I do this in English. I’m sure it’s going to be an enriching personal experience.

I’m looking forward to seeing you all there.

Posted in 1771, EuRuKo, javier ramirez, madrid, ruby, ruby, ruby on rails | Tagged: , , , , , , | Leave a Comment »

Upgrading to RadRails 1.2.1

Posted by javier ramirez on April 7, 2009

Aptana RadRails 1.2 is out there. If you are lucky enough, your Aptana installation will prompt you to upgrade and everything will go just fine.

In case your installation is a bit too old, or if you installed everything manually and when checking for updates Aptana says there’s nothing new, you can still install the latest version by using Eclipse “software updates”.

As Chris says in the forums, the update site for RadRails is http://update.aptana.com/update/rails/3.2/

When I tried to update by using that site, I got one error because this update depends on the latest version of Aptana Studio but, you guessed it right, Aptana check for updates insisted I had already the latest one.. but I knew I didn’t.

Once again, you can use Eclipse standard update procedure by using the Aptana Studio update site corresponding to your eclipse version, as explained here.

I’ve been using the latest version all day long and so far so good. It has some nice features like the rake files overview and the “explore files” option (I can finally say bye to the EasyStruts plugin), a polished interface, and improved compatibility with Eclipse 3.3 and 3.4.

Great work from the Aptana guys .

Posted in eclipse, javier ramirez, radrails, ruby, ruby on rails | Tagged: , , , | Leave a Comment »

Scotland on Rails 2009

Posted by javier ramirez on March 30, 2009

De vuelta de la conferencia Scotland on Rails me vuelvo con unas cuantas cosas aprendidas/confirmadas

a) Lo de menos son las charlas (aunque sigue siendo importante que, si las hay, sean interesantes). Lo que importa es el ambiente que se genera alrededor . Creo que el futuro de los eventos de desarrollo va por menos charlas, o por charlas filosóficas.

b) Tener un nombre en la comunidad no garantiza que seas competente haciendo presentaciones. Lo que sí garantiza es que te aplaudirán digas lo que digas (o leas lo que leas, aunque lleve años publicado y no tenga ningún interés).

c) El feedback positivo en una conferencia será directamente proporcional a la gente que venga de otros países. Se ve que la cortesía hace que evalúes bien aunque cometas el suicidio de no tener wifi en un sitio lleno de geeks, haya pocos enchufes, y des un catering de todo a 100.

d) La comunidad Rails hispana es muy potente, técnica y personalmente. El día que nos dé por hablar en inglés la vamos a liar parda. Da gusto escuchar a cualquiera de los de la representación “española” formada por Sam, Rai, Blat, Xavier, Alfredo, Gaizka, Susana, Fernando G., Sergio, Christos, Luismi, Guillermo, Felipe, David, Raúl, Juanjo, Jaime (y yo mismo :p )

En cuanto a las charlas, las que me inspiraron algo fueron (en orden cronológico):

– Getting Git, por Scott Chacon. Muy didáctico y con un buen balance entre crash course y consejos para usuarios más avanzados. Me gustó tanto que en cuanto su libro se publique es muy posible que lo compre. EPIC WIN

– Building blocks of modularity, por Jim Weirich. A pesar de alguna diferencia de criterio que tengo en las categorías de “connascence”, me pareció una charla muy interesante. Lo mejor es que no tenía nada que ver con Ruby o Rails. Era una charla de ingeniería/arquitectura de software. Así sí. EPIC WIN

– Security – what Rails will and won’t do for you, por Rory McCune. Sin entrar en nada especialmente novedoso, hizo una muy buena exposición de seguridad, comprensible, con ritmo, y con algunos datos que me parecieron interesantes. Es posible que acabe cambiando el login en alguna aplicación después de escucharla. WIN

– Advanced deployment, por Jonathan Weiss. Estuve a punto de perderme esta charla porque el nombre es muy engañoso, pero afortunadamente una amiga me hizo leer la descripción de la charla y acabé viéndola. No va de cómo hacer deploy, sino de qué forma puedes lidiar con una instalación compleja que requiere rendimiento, en concreto muy enfocado a la capa de datos. Explicaba las diferentes opciones para que tu base de datos escale, bien con replicación master-slave, master-master, particionado vertical de base de datos, sharding.. o mucho más sencillamente aplicando los famosos KISS y less is more. Me gustó ver que varias de las soluciones que aportaba las tenemos en producción en algunos proyectos. Siempre reconforta ver que lo que has hecho confiando en tu instinto es algo que tiene sentido. WIN

– The Ruby Object Model, por Dave Thomas. Nada nuevo que no esté escrito hace años (de hecho en los libros de este señor), pero de todos modos muy bien explicado y con unas referencias muy bien puestas a Simula y Smalltalk, incluída alguna frase lapidaria de Alan Kay. Lástima que no dedicase unos minutos más (dos) para introducir la teoría de objetos y el concepto de mensaje. Es lo único que le faltó para que me pareciera brillante. EPIC WIN

Y las charlas a las que asistí y que me hicieron sentir decepcionado:

– Keynote por Marcel Molina. Me alegro de que sepas leer y de que conozcas la página archive.org. El resto de la sala también tenemos internet en casa y también sabemos leer. Quizás sea especialmente duro porque en todas las charlas que he visto de Marcel me ha parecido brillante y esperaba mucho de esta keynote. FAIL

– Merb and Rails 3.0, por Yehuda Katz. Quitando el momento “teletienda engine yard de los primeros minutos”, me pareció en algunos puntos demasiado agresivo, en otros demasiado técnico, en otros demasiado ambiguo, y en otros pelín soberbio. Puede que por eso me dijeran que me parezco a él :P No me gustó su charla, pero he de reconocerle que de no haber sido por él puede que nunca se hubiera inventado el famoso juego “muerte violenta en seis movimientos”. De nuevo puede que sea un pelín duro porque Merb me gusta mucho y esperaba una charla espectacular. FAIL

– Server to server communication using XMPP and Ruby, por George Palmer. Dar una charla de XMPP sin hablar de XMPP y sin estar seguro de las siglas tiene su mérito. Dar una charla de 45 minutos en 20 tiene su mérito. Jactarse de no haberse leído un manual de 108 páginas porque es demasiado grande y luego no saber contestar a ninguna pregunta diciendo “pues esto estaría bien que lo hiciera, pero no sé si lo lleva”, tiene su mérito. Y a pesar de todo el FAIL no es absoluto porque la puesta en escena y la presentación multimedia me gustaron. Salvado por las slides de ser un EPIC FAIL.

A pesar de que el nivel de las charlas no me pareció óptimo y de que varios detalles de organización me parecieron muy malos (como que se llame “scotland on rails” y luego se quejen de que está demasiado orientada a Rails), el balance general que me llevo de la conferencia es bueno.

La experiencia fue muy interesante, la compañía inmejorable, y nada como ir a una de éstas para estar al día en tendencias de camisetas, zapatillas, y portátiles y gadgets cool ;)

Las fotos de la conferencia se están subiendo a flickr

p.s. gracias a aspgems por el detalle de hacerse cargo de mi viaje.

Posted in conferences, ruby, ruby, ruby on rails, ruby on rails | Tagged: , , | Leave a Comment »

Rails Hot Or Not. The Movie

Posted by javier ramirez on December 24, 2008

Una vez pasada la resaca de la conferencia Rails, y a punto de entrar en la resaca navideña, ya están subidos los videos de la conferencia rails 2008

Aunque pierde mucho enlatada, os dejo por aquí el video de la sesión Rails Hot Or Not

Y para que no se diga, también dejo la presentación que utilicé, convenientemente editada para que se vea en cada uno de los casos cuál fue el ganador elegido por la audiencia


Este material tiene una licencia Creative Commons Atribución-NoComercial-LicenciarIgual 2.5

Por supuesto, agradecer la participación y el buen rollo de los asistentes a la charla, que contribuyeron a que fuera un éxito.. aunque nunca llueva a gusto de todos ;)

searchwords: hot or not, conferencias, rails

Posted in conferences, conferenciarails, conferenciarails2008, development, javier ramirez, madrid, ruby on rails | Tagged: , , , , , , | Leave a Comment »

Instalando Rails 2.1

Posted by javier ramirez on July 9, 2008

Rails 2.1 mola.. la verdad es que trae un buen puñado de funcionalidades interesantes… yo le estoy sacando ya partido, por ejemplo, a los dirty objects (molarían aunque sólo fuera por el nombre) que son especialmente interesantes en callbacks y observers.

Si te interesa saber qué trae de nuevo la 2.1, un punto de partida interesante —aunque pelín básico en algunas partes— es el libro gratuíto “ruby on Rails 2.1: what’s new” . Por cierto, el primer cambio que aparece en la página 22 fue un patch mío… como se puede ver, el cambio fue humilde, pero el autor no :p

..a lo que iba… que Rails 2.1 mola… si consigues instalarlo. En muchos casos, es suficiente con un simple

gem install rails

Si es tu caso, puedes dejar de leer… pero lo que viene a continuación te interesará si al ejecutar ese comando te has encontrado con este error

ERROR: Error installing activesupport:
invalid gem format

La primera reacción es imitar a enjuto mojamuto y gritar “noooooo.. interneeeeeeeeé”

Una vez pasado el shock inicial, intentas volver a instalar… y cuando ya ves que no, buscas en el plugin google a ver si hay suerte y por lo menos esto le pasa a alguien más… y, efectivamente, hay más gente a la que le pasa.

Después de intentar diferentes cosas, la que me ha funcionado a mí ha sido irme a la página de active support en rubyforge descargar el fichero de la gema, y hacer la instalación local con el comando

gem install activesupport –local activesupport-2.1.0.gem

..y ya con esta gema instalada, podemos proceder a

gem install rails

El resto de gemas se bajan y se instalan correctamente desde el repositorio remoto

searchwords: rails 2.1, ruby on rails, gem install, github source

Posted in development, javier ramirez, ruby on rails, ruby on rails | Tagged: , , , , | Leave a Comment »