Una de las novedades de Rails edge es la inclusión de filtros y silenciadores en las trazas de nuestra aplicación. Los filtros permiten cambiar al vuelo contenidos de las líneas de traza en base a expresiones regulares y los silenciadores, más radicales, se limitan a tragarse las líneas de log que lo activen.
En Rails < = 2.2, si hacemos lo siguiente
$ rails test-exception $ cd test-exception $ script/generate scaffold blog $ script/serverY lanzamos un navegador hacia http://localhost:3000/blogs obtendremos una bonita traza de error como esta.
Sin embargo, en las versiones posteriores a Rails 2.2 la traza de error es mucho más escueta y por tanto más fácil de leer porque omite información que por lo general es poco necesaria. He aquí la nueva traza.
Como era de imaginar la cosa no acaba aquí sino que podremos configurar los filtros y silenciadores a nuestro gusto si editamos el fichero config/initializers/backtrace_silencers. Por ejemplo, con el siguiente cambio y con nuestra configuración de Rails
Rails.backtrace_cleaner.add_filter {|line| line.sub(/(\/opt\/local\/lib\/ruby\/gems\/1.8\/gems\/)([a-z]+)-([0-9.]+)\/(.*)/) {|match| " #{$2} (#{$3}) :#{$4}"} }conseguiremos que las trazas generadas por el código de las gemas aparezca mostrando el nombre de la gema y su versión. Puede verse aquí la traza que se generaría.
La semana pasada los desarrolladores norteamericanos celebraron el Día de Acción de Gracias, pero esto no se ha notado en el desarrollo de Rails. Las cosas se encaminan hacia la versión 2.3 de Rails.
Integración con RackLa base de script/server se ha reescrito y simplificado. Por ejemplo, la lista explícita de servidores soportados ha desaparecido y en su lugar Rails ahora depende de la instalación de Rack, y script/server hace esto – lo que quiere decir que ahora Rails soportará cualquier servidor siempre que Rack lo haga también.
Rutas más eficientesLas rutas han visto un par de cambios importantes esta semana. Los helpers de rutas que empiezan por formatted_ han desaparecido, y en su lugar ahora hay que pasar la opción :format al helper normal. De esta maanera se ahorra hasta el 50% de las rutas generadas para un recurso y esto puede ahorar una cantidad sustancial de memoria (hasta el 100MB en aplicaciones grandes según este ticket en Lighthouse) Si tu código utiliza los helpers formatted_ por el momento seguirá funcionando, pero debes tener en cuenta que estos helpers son «a extinguir» y que tu aplicación será más eficiente si adaptas tu código para usar el nuevo estándar. Otro cambio importante es que Rails ahora soporte múltiples archivos de rutas, en lugar de usar únicamente routes.rb Se puede usar RouteSet#add_configuration_file para incorporar más rutas en cualquier momentot – y sin borrar las rutas ya cargadas. commit commit
Mejor soporte de plugins de EnginesEl segundo cambio en las rutas permite soportar mejor los Engines: ahora se cargan y recargan automáticamente los archivos de rutas de los Engines (como en el resto de plugins) Pero los Engines están recibiendo más atención, además del enrutado: si tu plugin tiene un directorio app, entonces los directorios app/[models|controllers|helpers] se añadirán automáticamente al load path de Rails. Hay una discusión en curso acerca de cómo debería funcionar este mecanismo y cuánto reutilizar del plugin de Engines actual así que es posible que aún no hayamos visto los últimos commits en este aspecto. Los Engines ahora soportan la adición de paths para las vistas.commit commit commit commit
Volcados de los tests más sensatosSi usamos el plugin Quiet Backtrace de Thoughtbot, que nos permite eliminar selectivamente las líneas de los volcados generados por Test::Unit, nos agradará saber que han aparecido ActiveSupport::BacktraceCleaner y Rails::BacktraceCleaner en el core de Rails. Se soportan tanto filtros (para hacer sustituciones en las líneas de volcado usando expresiones regulares) como silenciadores (para eliminar líneas enteras). En las aplicaciones nuevas Rails añadirá automáticamente silenciadores para eliminar la mayor parte del ruido en los volcados de tests y construirá un archivo config/backtrace_silencers.rb donde poder configurar los nuestros. commit
Integración con Ruby 1.9Varios commits continúan avanzando en la compatibilidad con Ruby 1.9 y minitest para asegurar que Rails 2.3 está listo para funcionar con las nuevas mejoras en Ruby cuando sean lanzadas. Los que sigan el edge, sin embargo, deben tener en cuenta que uno de los últimos cambios en edge Rails depende de un parche al core de Ruby que aún no ha sido aplicado. También será necesario aplicar (temporalmente) el fork de Mocha de Jeremy Kemper para ser compatibles con MiniTest tal y como requiere este parche .
Tiempo de arranque más rápido en desarrolloJeremy Kemper y Josh Peek han estado trabajando para garantizar que haya partes de Rails y sus dependencias se carguen en memoria sólo cuando sea realmente necesario. Comprobad los commits del 23 de Noviembre para ver muchos cambios relacionados con esta recarga perezosa. Los frameworks Active Support, Active Record, Action Controller, Action Mailer y Action View ahora utilizan autoload para cargar sus clases individuales, y así mantener la carga de memoria lo más baja posible mejorando el rendimiento de Rails. commit commit commit commit commit
OtrosCon la nueva opción preload_frameworks se puede especificar si queremos que las librerías del core se autocarguen en el arranque. Por defecto es false de forma que Rails se autocarga pieza por pieza, pero en algunas circunstancias podríamos querer traerlo todo a la vez – por ejemplo Passenger y JRuby necesitan que Rails se cargue en su totalidad. commit
Los asset hosts son más flexibles, con las poisiblidad de declarar un host como un objeto específico que responde a cierta llamada. DHH ha proporcionado un proyecto de ejemplo, asset-hosting-with-minimum-ssl, que demuestra un buen uso de esta funcionalidad. commit
La ubicación de la carpeta de helpers es ahora configurable en una aplicación Rails ajustando ActionController::Base.helpers_dir, lo cual será una bendición para algunas circunstancias poco habituales – el caso de uso original es la construcción de una aplicación Rails que facilita la extensión mediante plugins en lugar de mediante la alteración de la propia aplicación. commit
La generación de tokens de protección contra CSRF se ha simplificado, y ahora Rails utiliza una cadena aleatoria generada por ActiveSupport::SecureRandom en lugar de trastear con los IDs de sesión. Como resultado de esto las opciones :digest y :secret de protect_from_forgery están obsoletas y no surtirán ningún efecto a partir de ahora. commit
Y ya que hablamos de secretos, seguro que algunos encontrarán algún uso original y útil de ActiveSupport::MessageEncryptor, que proporciona una forma sencillo de cifrar información para su almacenamiento en lugares no seguros (como las cookies). commit
La función de Active Support from_xml ya no depende de XmlSimple. En su lugar, Rails ahora incluye un su propia implementación de XmlMini con sólo la funcionalidad necesaria, de forma que Rails puede dejar de incluir la copia de XmlSimple que venía arrastrando. commit commit
Como se recordará, las mejoras de la semana pasada incluyeron el cambio de nombre de application.rb a application_controller.rb. Esta semana hay una nueva tarea de Rake, rake rails:update:application_controller que hace esto automáticamente y que forma parte de la tarea rake rails:update. commit
Hay buenas noticias si usamos ActiveSupport::OrderedHash: por fin implementa each_key y each_value. commit
Se ha internacionalidado un poquito más del core de Rails: las unidades usadas por number_to_human_size. Si mantienes un archivo de traducciones, ahora tienes que añadir las traducciones de las unidades de almacenamiento: bytes, KB, MB, GB, TB. commit
Por fin ha desaparecido el soporte de los componentes en Rails, que fueron en su momento según «Agile Web Development wih Rails» un brillante ejemplo de lo que ocurre cuando la ambición se impone a la prudencia. Por si un par de años de advertencia sobre lo que iba a ocurrir no fue suficiente, ahora es el momento de encontrar una solución alternativa. commit
Han dejado de generarse por defecto un par de archivos en /public que tenían que ver con los dispatchers de CGI y FCGI. De todas formas, si te hace falta, puedes obtenerlos añadiendo la opción --with-dispatches al ejecutar el comando rails, o bien generarlos después usando rake rails:generate_dispatchers). commit commit
Paseando hace unas semanas por la ciudad sueca de Helsingborg me llamaron la atención estas estatuas en ropa interior.

Estatuas en ropa interior — Helsingborg — Suecia
Lo que no sé es si fueron unos vándalos o si era publicidad de alguna tienda de lencería.
This I tell to myself when I wake up everyday, to cope with the myriad of annoying little things the iPhone has.
You see, we’re better because:
If this doesn’t work, repeat the mantra with me:
There’s no UI but Apple’s touch UI.
Nokia is getting it all wrong.
I don’t really want a Nokia.
Gaaahhhh!!!
What kind of fruit is a Nokia anyway?
I’m a fan of David Allen’s Getting Things Done (GTD). I also have an iPhone, so for me it’s quite the perfect device for tracking my next actions and projects because it’s always with me.
After trying a bit OmniFocus for iPhone, I decided it was way too complex for what’s needed for a practical GTD implementation, and that synchronization pretty much sucked because an Apple MobileMe account is a must. Following David Allen’s own advice, a simple to-do list will suffice. That’s why I decided to go with Appigo’s ToDo1.
A friend of mine is a great fan of GTD-friendly web application Remember the milk. I decided too to give it a try and I created a free account. I heard that it was possible to synchronize it with ToDo so I thought it would be nice to use them together.
But no. Yesterday, configuring ToDo in my iPhone I discovered that Remember the milk folks force you to have a “pro” account (meaning paying for the service) to have synchronization with ToDo. I guess all because they have their own iPhone application, that only works online2. Bummer, and not the way to go for sure.
Fortunately, there’s another (and no, it’s not Leia Organa): Toodledo. I configured my account there, tested the web application a bit, configured my iPhone’s ToDo app and voilá, synchronization is working perfectly. List management is quite nice, and it even supports bulk task-loading when you’re craving for getting a bunch of task out of your mind.
So, Venera7’s recommendation for GTD with iPhone and your computer: Appigo’s ToDo and Toodledo.
NotasIf my changes worked, this post should have an IntenseDebate-style commenting feature instead of the default one provided by TypePad. You can give it a try or just ignore.
Updated: Testing slight template change
Escenario: trabajo en, por, para, (y a veces contra :) una PYME y llega el feliz día en el que hay que incorporar a alguien más al equipo. Hay que ponerse a buscar.
Empiezas por echar mano de los servicios consolidados, las bolsas de empleo más “tradicionales”: Infojobs y sus seguidores. Te molestas en darte de alta, publicar la oferta, pagarla, y te sientas en tu cómoda butaca a ver como llegan interesantísimos CVs.
Aquí suelen ocurrir dos cosas:
Por el camino, como ves que no llegarás muy lejos con esta metodología (no dudo que habrá a quien le sirva, a mi solo me ha servido con resultados satisfactorios un 10-15% de la veces que hemos contratado a alguien), empiezas a probar otras formas:
Piensas en personas de tu entorno que podrían conocer a alguien que se ajuste al perfil y mandas algún email; publicas la oferta en tu blog; lo mandas a sitios acordes al target (Barrapunto si buscas programadores, por ejemplo); twitteas que buscas a alguien...
Y el método supremo: esperas a que se produzca una conexión inesperada (es una espera activa, claro está, pero el componente de casualidad tiene muchísimo peso, unido a las conexiones sociales-personales).
Para muestra un botón: justo esta tarde hemos contratado a una persona que es la hermana de una amiga de la hermana de la novia de una persona de la oficina (si, hay varios hermanos en la ecuación, no es un error de transcripción). No son cuántos grados son estos, me pierdo contando…
En mi caso todo esto suele ser lo que mejor funciona: conexiones personales y casualidades.
Pero todo esto provoca una ineficiencia en la gestión de estos perfiles. Hay CVs que te llegan a una cuenta de correo, otros a otra, otros te llegan por Skype, otros son una URL a un perfil online… No me dedico a RRHH pero me vendría estupendamente tener ordenaditos todos los CVs que he ido manoseando con los años.
Creo que hay espacio para una nueva categoría de producto: un sistema para hacer una gestión personal de los CVs. No desde el punto de vista de los RRHH tradicionales de una empresa, en la que todo bascula en los ejes empresa-oferta-candidato, sino desde un punto de vista personal, en el que yo conozco a una persona (puedo ser yo mismo) que necesita un perfil determinado. O yo conozco a gente que sabe hacer ciertas cosas, cosas que en un momento dado pueden ser de utilidad para gente que conozco.
No se trata de que todos nos convirtamos en mini-gestores de recursos humanos, sino de disponer de una herramienta que facilite y potencie esas dos cosas que tan bien funcionen: las conexiones personales y las causalidades.
¿Cómo? Buena pregunta. Pero me imagino una capa de funcionalidad encima de Facebook que permita circular este tipo de información, o un cruce de LinkedIn con todo lo social que nos da Facebook.
Además, incidiendo en lo social, esta herramienta también tendría una sección de reviews sobre empresas. Un 11870 o un Ciao con opiniones sobre empresas, pero desde el punto de vista de trabajar para una empresa. Se hablaría de lo agradable o no de trabajar allí, la calidad de los jefes y compañeros, el tipo de trabajo, los proyectos…
Y como una cosa así en plan abierto sería una locura y un descontrol, de nuevo añadimos la capa de amistad y la identidad como mecanismo para el autocontrol: tú solo verías las opiniones que dejen tus amigos (y un segundo grado, tal vez). Si todas las opiniones van firmadas, y si son tus amigos quienes van a leerlas, te preocuparás de dar comentarios con valor y comedidos.
Creo que una cosa así acabará por llegar… ¿Alguien se viene a Long Bets a apostar para dentro de 10 años?
Escenario: trabajo en, por, para, (y a veces contra :) una PYME y llega el feliz d??a en el que hay que incorporar a alguien m??s al equipo. Hay que ponerse a buscar.
Empiezas por echar mano de los servicios consolidados, las bolsas de empleo m??s “tradicionales”: Infojobs y sus seguidores. Te molestas en darte de alta, publicar la oferta, pagarla, y te sientas en tu c??moda butaca a ver como llegan interesant??simos CVs.
Aqu?? suelen ocurrir dos cosas:
Por el camino, como ves que no llegar??s muy lejos con esta metodolog??a (no dudo que habr?? a quien le sirva, a mi solo me ha servido con resultados satisfactorios un 10-15% de la veces que hemos contratado a alguien), empiezas a probar otras formas:
Piensas en personas de tu entorno que podr??an conocer a alguien que se ajuste al perfil y mandas alg??n email; publicas la oferta en tu blog; lo mandas a sitios acordes al target (Barrapunto si buscas programadores, por ejemplo); twitteas que buscas a alguien...
Y el m??todo supremo: esperas a que se produzca una conexi??n inesperada (es una espera activa, claro est??, pero el componente de casualidad tiene much??simo peso, unido a las conexiones sociales-personales).
Para muestra un bot??n: justo esta tarde hemos contratado a una persona que es la hermana de una amiga de la hermana de la novia de una persona de la oficina (si, hay varios hermanos en la ecuaci??n, no es un error de transcripci??n). No son cu??ntos grados son estos, me pierdo contando…
En mi caso todo esto suele ser lo que mejor funciona: conexiones personales y casualidades.
Pero todo esto provoca una ineficiencia en la gesti??n de estos perfiles. Hay CVs que te llegan a una cuenta de correo, otros a otra, otros te llegan por Skype, otros son una URL a un perfil online… No me dedico a RRHH pero me vendr??a estupendamente tener ordenaditos todos los CVs que he ido manoseando con los a??os.
Creo que hay espacio para una nueva categor??a de producto: un sistema para hacer una gesti??n personal de los CVs. No desde el punto de vista de los RRHH tradicionales de una empresa, en la que todo bascula en los ejes empresa-oferta-candidato, sino desde un punto de vista personal, en el que yo conozco a una persona (puedo ser yo mismo) que necesita un perfil determinado. O yo conozco a gente que sabe hacer ciertas cosas, cosas que en un momento dado pueden ser de utilidad para gente que conozco.
No se trata de que todos nos convirtamos en mini-gestores de recursos humanos, sino de disponer de una herramienta que facilite y potencie esas dos cosas que tan bien funcionen: las conexiones personales y las causalidades.
??C??mo? Buena pregunta. Pero me imagino una capa de funcionalidad encima de Facebook que permita circular este tipo de informaci??n, o un cruce de LinkedIn con todo lo social que nos da Facebook.
Adem??s, incidiendo en lo social, esta herramienta tambi??n tendr??a una secci??n de reviews sobre empresas. Un 11870 o un Ciao con opiniones sobre empresas, pero desde el punto de vista de trabajar para una empresa. Se hablar??a de lo agradable o no de trabajar all??, la calidad de los jefes y compa??eros, el tipo de trabajo, los proyectos…
Y como una cosa as?? en plan abierto ser??a una locura y un descontrol, de nuevo a??adimos la capa de amistad y la identidad como mecanismo para el autocontrol: t?? solo ver??as las opiniones que dejen tus amigos (y un segundo grado, tal vez). Si todas las opiniones van firmadas, y si son tus amigos quienes van a leerlas, te preocupar??s de dar comentarios con valor y comedidos.
Creo que una cosa as?? acabar?? por llegar… ??Alguien se viene a Long Bets a apostar para dentro de 10 a??os?
Ernesto Frías publica en EX7 una entrevista que contesté sobre unvlog.com (en realidad alguna de las respuestas es de Blat). Si llegas al final, descubrirás nuestras webs favoritas.

Este finde le pegué un lavado de cara al planeta que me hice en agosto y ha quedado precioso, cheiquirau: Planeta denegrez.
Si alguien quiere cotillear la hoja de estilos, aquí está.
Este año no voy a tener tiempo de comentar, tal y como hice el año pasado, las charlas a las que he asistido en la Conferencia Rails 2008. A lo que sí me he animado es a realizar un video con una selección de 37 imágenes. Las fotos están sacadas por mí, y tengo que reconocer que era la primera vez que sacaba fotos en modo manual, así que entre las condiciones de luz un tanto extremas y lo inexperto del fotógrafo, no esperéis gran cosa.
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/IfU-zrkpr7w&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/IfU-zrkpr7w&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
La canción del video es “Eterno domingo”, del grupo Los Sundayers. Uno de los miembros del grupo asistió a la Conferencia Rails y repartió copias de su disco, también llamado “Eterno domingo”. Da gusto ver que hay grupos que se animan a publicar sus obras con licencias Creative Commons.

This days I have been working on a small library for the i-Buddy device, a small gadget for MSN Messenger lovers, that you can connect to your computer through a USB port and has some functionality like light its head with different colours, light a small hearth, move the flaps and turn left or right.
The main attractive is the price (no more than 25 €) and the simplicity.

The library result of my work is rubi-buddy, and works with Ruby and ruby-usb, and its inspired in the one that developed at 11870.
The library is in progress, because I still have to implement the flap movement. Also, I want to add more examples in the project. At this moment there is only one that checks the response code from La Coctelera and turn the head light green or red.
If you are interested, I encourage you to use it and to add more examples.
I'm super busy with my duties as technical chair and M.C. for the conference and I'm not getting the opportunity to live-blog the Professional Ruby Conference the way I would like to. Luckily Nick Quaranto is doing a great job documenting the proceedings in details here: Professional Ruby Conference Notes
Liana (with baby in tow sometimes) is also doing a great job of documenting the highlights of the sessions.
So far it's been a really great experience. Along with friends and familiar faces, I'm also meeting amazing people from all sorts of backgrounds and it's doing wonders for my reputation (heh!)
The single track, 30-minute format is wonderful and we've gotten ample praise about it. Everyone in the audience gets the same content at the same time and has plenty of opportunities to meet informally and discuss what was presented. We have quite a mix of experience levels in the audience -- keeping the talks short and sweet ensures that no single group is bored for an extended period of time. We've covered the gamut of topical ranges, from pure case study "this is what we did" in the New York Times newsroom to Philippe's detailed explanation of DTrace.
Our Tuesday morning keynoter, Giles Bowkett, canceled at the last minute, so I had to scramble. After some undecidedness, I opted to try a concept that I witnessed last week at Conferencia Rails in Madrid. Sebastian Delmont and I brainstormed the content over single-malts in the hotel bar last night.
Photo credit: Sebastian Delmont
We distributed two pieces of colored paper to each person, which they used to vote on their preferred choice from the two displayed on the screen. After most of the votes, I asked for the audience to chip in with an explanation (and occasionally apology) for their choice.
Photo credit: Sebastian Delmont
I was asked to post the results, so here is my list of the smackdown lineup:
vim vs emacs: About half of the audience voted, skewed heavily to vim. I didn't want to start a "religious war" so I didn't ask for elaboration.
svn vs. git: Heavy voting, with fairly even split (perhaps slightly skewed to svn). Will from
jQuery vs. Prototype Apparently when I introduced this lineup I said "...still using Prototype" which I apologize for, since it was leading the audience and it got a laugh. I've been a fan of Prototype for a long time, but Hashrocket as a whole has switched over to jQuery in the last 6 months.
Chad Pytel told us that he's still using Prototype on existing projects because it doesn't make sense to switch over, essentially "if it's broke don't fix it".
Sinatra vs. Camping A few people in the back of the room voted for Sinatra. Matt Bauer told us that it's good for very small standalone web apps and yes, it's ready for production-use.
Blueprint vs. YUI About half the audience voted, skewed towards Blueprint. Someone pointed out that the 960 Grid System is cool, and then we spent at least 30 seconds trying to figure out the name and URL.
MySQL vs. Postgres Heavy vote for MySQL. Consensus appears to be that if you come from big enterprise databases then you're going to prefer Postgres. Also, Postgres is more standards-compliant and
blank? vs. empty? This one was a joke (pretty much) that Sebastian and I included in the smackdown to remind the audience to consider the semantic meaning of API methods. The correct vote would have been for both, since they are not used for the same purpose. The blank? method is for strings and returns true for strings consisting of purely space characters. The empty? method is primarily meant for arrays, but works on strings and returns false for strings consisting of purely space characters.
attachment_fu vs. paperclip Evenly split audience, but consensus was that Paperclip is better than attachment_fu in terms of features and flexibility and its implementation code is very clean and easy to figure out. Also, paperclip allows for attaching more than one file to a single model.
system gems vs. frozen gems Frozen gems won hands-down. Bryan Liles said that if anyone thinks system gems is the way to go then obviously they aren't doing production deployment. Sebastian chimed in that using system gems saves 10 seconds on his deploy time, which everyone took as a joke. Not sure if he meant it seriously. :)
Vlad vs. Capistrano A handful of people voted for Vlad, but otherwise the audience favored Capistrano heavily. I asked Matt Bauer to defend Vlad. He mentioned some reasons about its simplicity and how bad early versions of Capistrano were, but in the end he said it's not worth switching at this point because the pain-points of Capistrano have been resolved.
Mocha vs. Flexmock Mike Schwab was the only person who voted for Flexmock, but wasn't really able to defend the choice except to tell us that Chad Fowler and Marcel Molina suggested it once at a conference. (Comments welcome -- Is this reason still valid? Was it ever?)
FactoryGirl vs. ObjectDaddy Not too many people voted and those that did went for FactoryGirl. Earlier in the conference we heard from the testing panel that ObjectDaddy has way too much magic to be useful.
resource_controller vs. make_resourceful A couple of people voted for each. Got the impression that the audience was largely unfamiliar with these great plugins, so I asked Joe Fiorini to explain them. Bottom line, if you're writing your apps in a RESTful manner then you should check out and use one of these libraries because it'll spare you a bunch of boilerplate code.
HAML vs. ERB One of my favorite topics! The split was maybe 33% HAML with surprisingly heavy voting. The reasons for sticking with ERB? Mostly to keep designers happy or based on what I detect as a resistance to change. I gave my typical impassioned explanation of how HAML lessens the amount of mental mapping needed to effectively think of your views as semantic markup and match them to your CSS.
Bluecloth vs. Redcloth Meh...
RMagick vs. ImageScience Meh...
TinyMCE vs. FCKEditor Rich-text editor widgets in Javascript. They're not that different from each other and the audience was all like, "Meh.." :)
restful_authentication vs. clearance This one was funny. A handful of votes went up for Clearance, which disturbed its author, Chad Pytel. He stood up and told us not to use it since it's not ready. The offshoot of Github's popularity, is that once public projects go up, they start getting used -- whether they're ready or not. :)
Test::Unit vs. RSpec I was pretty much out of time at this point, so I skipped a bunch of slides to this matchup. Even distribution and some confusion about whether Shoulda belongs to TestUnit (yes) or RSpec. I think the consensus is that it doesn't matter as long as you're putting some effort into testing. I wondered to myself if the people that didn't vote weren't doing any testing. Things that make you go "hmm..."
If you're so inclined, take a moment to tell me your vote for the following smackdown matchups that I didn't have time to get to in the session...
Mongrel vs. Passenger
Sphinx vs. SOLR
ThinkingSphinx vs. UltraSphinx
exception_noti???er vs. hoptoad
Gruff vs. Google Charts
CouchDB vs. SimpleDB
No ha habido mucha actividad, en términos de grandes cambios o nuevas funcionalidades en el core de Rails. Así que lo mejor es dirigirse a los logs
de los commits en busca de cambios menores o correcciones. Ha habido algunos avances en la refactorización y sorporte de threads en ActionPack, así como alguna actividad en ActiveModel, pero nada realmente concreto.
script/server ahora comprueba si Thin está instalado y lo utiliza. Esto es bastante cómodo si usamos Thin como nuestro servidor en producción y queremos usarlo también en desarrollo. Hay que añadir config.gem ‘thin’ al fichero environment.rb.
Este parche ha sido contribuido por uno de los chicos de fluxin, y estos son los cambios
Personalización de String#humanize mediante reglas de inflexiónLa extensión String#humanize del core se utiliza para convertir cadenas con guiones bajos, por ejemplo nombres de tablas, en texto legible. Por ejemplo:
"Actor salary" "anime_id".humanize => "Anime"Pero a veces esto no funciona tan bien, cuando tenemos tablas heredadas de otra aplicación o simplemente con nombres inhumanos como “act_sal_money” (que sería humanizada como “Act Sal Money”)
Ahora podemos especificar nuestras propias reglas de inflexión (igual que puede hacerse para personalizar las reglas de inflexión para plurales, singulares, etc.)
Inflector.inflections do |inflect| inflect.human /_cnt$/, '\1_count' inflect.human 'act_sal_money', 'Actor Salary' endObsérvese que podemos usar expresiones regulares para convertir por ejemplo columnas como “click_cnt” en “Click Count”
Demos las gracias a Dan Manges y Pascal Ehlert por este cambio.
Condiciones sobre múltiples tablas utilizando hashesPratik ha entregado un pequeño (pero útil) cambio en ActiveRecord que permite especificar las condiciones de una tabla sobre la que se efectúa un JOIN en su propio hash. Por ejemplo:
Anime.all( :joins => :character, :conditions => { :active => true, :characters => { :gender => 'female' } } )La sentencia anterior encontrará todos los animes “activos” con personajes femeninos. Cambios
Lo más importante esta semana en el desarrollo de Rails es el inminente lanzamiento de Rails 2.2.1 -también conocido como Rails 2.2 RC2. Debido a eso ha habido algunos cambios significativos en el repositorio de Rails.
En primer lugar, es probable que sea necesario actualizar rubygems para ejecutar RC2: ahora requiere la versión 1.3.1 de rubygems, que fue publicada exactamente ayer. Esto hará más util y estable la posibilidad de poner gemas en el directorio vendor, aunque a costa de una actualización que puede resultar algo costosa. En este artículo se pueden encontrar algunas soluciones. commit
También se ha trabajado bastante en el motor de rutas durante la semana pasada. Jeremy Kemper entregó bastantes correcciones que minimizan la creación de objetos y expresiones regulares, recortando así el uso de memoria. commit commit Ahora tenemos las las opciones :only y :except para invocar a map.resources, que también harán descender el uso de memoria si usamos muchas rutas de recursos -véanse estos artículos para entrar en detalle (aunque también ha habido algunos retoques a la manera en que funcionan los recursos anidados después de que se publicase). commit commit commit
El nuevo código de pooling de conexiones de ActiveRecord ha sido afinado un poco también, evitando algunos problemillas con el adaptador de Oracle y siendo un poco más eficiente en modo desarrollo. commit
Las URLs polimórficas son ahora más intuitivas si uno de sus parámetros es nil. Por ejemplo, llamar a polymorphic_path([@project, @filter, @issue]) con un filtro nulo ahora devuelve project_issue_url en lugar de NoMethodError. commit
Se ha limitado la funcionalidad de protección contra request forgery de forma que sólo se aplica a peticiones que solicitan contenido formateado en HTML. Ha habido una gran discusión en el ticket de Lighthouse que llevó a este cambio, pero se resume en que la implementación anterior tenía fallos que hacían que las acciones destroy fueran inaccesibles cuando se usaba XML. Además, los otros tipos de peticionese pueden proteger por otros medios. commit
Or how to turn your Intel based Netbook into a Macbook nano and not spend 1600 euro trying1.
A couple of months ago both crews of Venera7 and El Geek Errante, driven by the geeky rush of the moment, decided to buy the quite sexy netbook from Acer, the Aspire One. The idea was to have something extremely light and portable that could be carried in a small bag with a book and some other small stuff.
The Acer Aspire One has a nice set of features: a 9″ LED backlit glossy screen, 120Gb HD, a really small factor, 2 USB ports, 1Gb RAM (expandable to 1.5Gb), an Intel Atom 1.6GHz processor and an integrated Intel GMA 950 video card. And all for 350 Euro (taxes included). It’s quite easy to find in Spain and I guess in general around the world. We bought our white ones at PC City in Madrid; I guess after that they ran out of stock for the weekend in the white model :-)
We thoroughly evaluated the MSI Wind, the Dell Inspiron Mini, the HP whatevermodelitisthatisverysmall, and the Asus Eee PC. Turns out in terms of features/usability/size the Acer is the best option. Basically, MSI Wind and Dell are too big, HP is too slow, and Asus Eee PC is too crappy and too small (keyboard is for children). Anyway, go to Youtube and see the reviews, comparisons and tour de forces by yourself.
Surprise, I´m not only installing Mac OS X!Yep buddies, that´s right. I´ll also explain how to repartition the internal disk to have Mac OS X as the main OS and a small Ubuntu partition for Linux stuff (like wireless hacking), install both operating systems, and configure GNU´s Grub to be able to dual boot them.
The plan will be to partition the Aspire One internal disk into three different physical partitions: first one for Mac OS X (110Gb), second one for Ubuntu Desktop (9Gb) and the third one for Linux swap space (1Gb).
I´ll explain all the details in the upcoming sections.
What will work and what won’tEverything will work charmingly (including the official Apple Mac OS X updates and the integrated webcam) except for the following things (that we´ll try to minimize with different software toys):
If you have already googled about the Acer Aspire One and Mac OS X, yes, everything else is working. Amazing, huh? Just wait to see the steps to tune up your little creature!
Hardware you’ll needFirst of all, as I’ve already said, you don’t need to do this if you don’t want to either upgrade your memory or change your wireless card, although the latter is strongly recommended because it doesn’t make much sense to have a netbook that isn’t able to surf wirelessly, doesn’t it?
So, let’s assume you’re convinced and you’ve already purchased and received all your gear (typically for Spain the Dell WiFi card delivery takes 2-3 weeks).
Now breath deeply: you’ll have to open your Acer Aspire One. Fear not, my friend, because the operation is quite easy. What I’ll do here is point you to the best Aspire One hacking tutorial out there and just make some comments and remarks about what we’re interested in.
The Aspire One hardware hacking tutorial is a video made by TnkGrl that explains in very detail how to open it. Go there, watch it a couple of times, get the necessary gear to open it and follow her instructions while you´re opening your Aspire One.
So go watch it now!: Tnkgrl awesome Acer Aspire One hacking tutorial
My comments to the video:
If the process went OK and the original Linpus that came with the Aspire One is still installed, you should be able to see the upgrades from the OS. Don´t worry now, because we´ll see them as soon as Ubuntu Desktop and Mac OS X are installed.
Updating the Aspire One BIOSTo smoothly install Mac OS X in our computer, we´ll have to update the BIOS firmware with the official Acer BIOS update release 3304 you just downloaded. Here´s the detail of what´s inside the download from Acer:
The Aspire One is able to boot from external USB devices. Thanks to this, we´ll be able to upgrade our software without having to waste a DVD: we´ll just boot an MS-DOS compatible operating system from an external USB drive that has inside the proper upgrade image files and programs.
Now, for doing a bootable USB drive you have mainly two options: do it with Mac OS X or do it with Linux or Windows. The latter is pretty well documented in the Internet, so I won´t go with this one. Alternatively, I chose to make my life a bit more complicated and fight with the method to create bootable USB drives from Mac OS X. Once again, it´s not difficult, it was just poorly documented until now.
So, we´ll create our FreeDOS bootable USB drive and we´ll transfer the two necessary files for flashing our BIOS. The FreeDOS image will have to have enough room to host the extra BIOS flashing files. That´s the reason I´ve chosen to download a 11.52Mb image instead of the traditional floppy images. Anyway, here are the the steps to follow to create the flashing USB drive and update your Acer BIOS:
You should see a new /dev/disk device that corresponds to your USB drive. In my case, it was /dev/disk1 so from now on I´ll assume this is yours too.
Be careful because we´re going to completely erase the USB drive. If you have data inside it you want to keep, do a backup now.
The dd command copies bit by bit the FreeDOS image to your USB drive, so now you have a DOS bootable USB drive.
This creates a new file in the USB drive root called ZG5_3114.FD containing the actual BIOS. If anything goes south, we´ll always be able to recover our previous BIOS with this file following the instructions you have in Aspire One User Forums
Wait until the process is over. The Aspire One should restart automatically. When done, hit F2 to go to the BIOS setup utility and check that System BIOS information now points to v0.3304
That´s all.
Installing Ubuntu Desktop and configuring multiboot with GrubWhy install Ubuntu in the Aspire One?
Several reasons: it rocks, it’s perfect for wireless hacking if you’re on the go, and it gives you more control over what’s going on with your laptop. Ubuntu Desktop is a supported operating system for the Aspire One, so it’s only a good idea to have it. Besides, it’ll help us partition the Aspire One internal disk and boot Mac OS X properly.
I won’t go with a lot of detail for the Ubuntu installation in your Aspire One because the process is quite standard and well documented. The only three important steps for me were getting the Ubuntu Installation disk in an USB image, the disk partitioning and, of course, Grub configuration that’s far from obvious.
As I’ve already told you, I don’t have an external USB DVD drive, so what I did to install Ubuntu in my Aspire One was to burn and Ubuntu Live cd with the image you just downloaded from the download lists provided before, boot it in an Intel-based computer (your Mac, for example), and follow the instructions in Ubuntu community forums to create a bootable Ubuntu USB distribution. If it has enough space, use the USB drive you just used for upgrading your bios, or the one you’re going to use for Mac OS X Kalyway installation. It really doesn’t matter because you’ll use the Ubuntu bootable USB drive just once.
So, now you’ve got an Ubuntu bootable USB drive. Boot it in your Aspire One by hitting F12 and selecting the external USB drive to boot and start the installation. In my case, using the Ubuntu installer, I chose manual partitioning of the Aspire One disk. I made three partitions: the first one for Mac OS X, was about 110Mb. Second one was for Ubuntu, 8Gb, and the third one took the remaining disk space for Linux swap. Of course, I proceeded to install Ubuntu in the second partition using the third one as swap. When assigning mounting points to the partition, I told Ubuntu installer to locate boot information in /boot under the root directory in the second partition (the one prepared for Ubuntu). It’s there where we will be installing the PC_EFI boot necessary to boot Mac OS X.
Once Ubuntu is installed, boot it in your Aspire One, and prepare to do some administration to configure Grub as the multiboot program. These are the steps I followed to be able to boot Mac OS X after its installation:
Now you should be able to boot Mac OS X once it’s installed. I also tried this procedure with Chameleon EFI and for some reason it didn’t work, so PCI EFI is the one I’m recommending here.
Preparing Mac OS X installationThe Aspire One is now prepared for the Mac OS X Kalyway installation. Next steps will describe how to set up your USB drive to get a bootable Mac OS X image. You don’t need that if you have a working external USB DVD to use Kalyway DVD.
Did it work? Is your USB drive booting? Great, the following is where the rubber hits the road.
OK, Mac OS X is now up & running in your Aspire One, but we’re far from finished. Let’s go through the steps necessary to get it ready to use in the following section.
Upgrading your Mac OS X and post-installation stepsHere’s is where we take our Mac OS X to its latest version (at the time of writing this post, it’s 10.5.5) and do some tweaks to have as much as possible working in our personal MacBook nano.
We’ll need to have most of the stuff we listed as software downloads available for the Aspire One so Primo) you have it in an external USB drive that you’ll be plug in into the Aspire One or Secondo) you have now Internet connection from your MacBook nano so you’re able to download it from the Internet.
Currently we are using 9.2 Speedstep Kernel, but we want to use Vanilla Kernel from the original Mac OS X because it’ll allow us to get all the software updates from Apple. We will be installing it in the following steps, but we have to be ready for it. This means we’ll have to make some configuration changes in Mac OS X because for this system vanilla kernel will only support 1 cpu.
With your favorite editor, edit the /Library/Preferences/SystemConfiguration/com.apple.Boot.plist file to do the following modifications (you could open a Terminal and use vi or just use the Editor program located under ‘Applications’ > ‘Utilities’). Inside the file, look for “Kernel Flags”, put there “cpus=1″ and save the file.
Keep this window open while you run the downloaded update and install it.
Keep this window open while you run the downloaded update and install it.
System will take a long time to reboot let the system be until it will restart, so be patient and give it plenty of time. If in case you run out of patience or it will not reboot you have to do hard reboot on the system and use “update –v” steps on boot you’ve already seen here.
Now you’re Mac OS X is Leopard 10.5.5. You’ve got still some steps to perform to get some things running, so let’s go for them.
Making the sound work
Fixing the “About this Mac” message
Getting 1024×600 resolution
Getting the network plug & unplug to work
Getting the battery indicator to work
Avoiding system shutdowns while closing the lid
This one is really easy. Just install InsomniaX (the link is also in the ‘Software you’ll need’ list) and configure it to fire up every time you start your Mac OS X. This can be done going to System Preferences > Accounts, clicking on your account and going to the ‘Login Items’ tab. There you can click on the ‘+’ button and add InsomniaX to the list.
And that’s all, my friends. You should be able to go to the Apple menu and click on ‘Software Updates’ to get the latest updates from Apple, and also download and install your favorite Mac OS X applications.
Enjoy the fruit!
AcknowledgementsHere’s the list of people that has been done possible this step by step tutorial:
Me parece que estoy usando Windows Mobile cada vez que me sale este aviso:

He llegado a la conclusión de que la diferencia básica entre Windows y Mac OS es que éste tiene menos cosas que me molestan.
Si en una interfaz ofrecemos una acción que, al ser realizada, resulta en una calle sin salida que el usuario sólo puede aceptar cabizbajo, es que hemos hecho algo mal. Piensa en dar una alternativa más satisfactoria, qué sé yo: “para abrir más páginas, se cerrará wadus.com, que abriste hace 4 días”.
Antes que nada esta semana, una advertencia para aquellos que no sigan de cerca el estado del repositorio de Rails – “edge” ahora significa el filo de la navaja. Ya se está preparando el lanzamiento de la release 2.2 y el repositorio se ha bifurcado; por el momento la versión edge de Rails se identifica como 2.3 , aunque el número de versión podría cambiar más adelante. Si queremos instalar la versión 2.2 en nuestra máquina, deberíamos asegurarnos de que estamos usando la rama 2-2-stable, y no edge, que está sufriendo cambios profundos.
El código en 2-2-stable aún sigue viendo cambios, pero son pequeños ajustes. Esta semana, se trata de corregir un bug en la asignación en asociaciones has_one :through , más ajustes a la protección CSRF , y una correción a la manipulación de checkboxes para valores booleanos, así como la actualización de las copias incluidas de TZInfo, Prototype, script.aculo.us. También se ha avanzado en la compatibilidad con Ruby 1.9 (aunque el objetivo de soportar Ruby 1.9 en sus totatlidad está planteado para Rails 2.3).
Las mayores modificaciones en la rama 2.2 es la adición de soporte explícito de internacionalización en los proyectos Rails recién generados, incluyendo un archivo de locale de ejemplo, la autocarga de todos los locales que existan en config/locales y configuración de ejemplo en config/environment.rb. commit
También es destacable que en 2.2 se ha eliminado un buen trozo de código, desapareciendo de los casos de tests de ActiveRecorod todo un embrollo de casos especiales para el adaptador de SQL Server. Ken Collins ha hecho un tremendo trabajo consiguiendo que el adaptador de SQL Server funcione de la manera que Rails espera que lo hagan los adaptadores, lo cual es un gran pasado en el área de la portabilidad de los adaptadores. commit
En cuanto a la rama edge, ahí tenemos todavía más acción dado que en esta rama recién abierta acaba de entrar un montón de código que estaba esperando su momento. Corren tiempos interesantes y merece mucho la pena descargarse edge. Pasemos a ver algunos de los cambios más notables de la última semana.
Muchos cambios son obras de Jeremy Kemper, que ha estado mejorando los tests internos de Rails para cambiar de Test::Unit::TestCase a ActiveSupport::TestCase. Esto incluye también el requisito de usar Mocha para testar Rails (en el código 2.2, si no tenemos Mocha instalados, algunos tests serán ignorados), así como hacer que la estrategia de testing en Rails (tanto en el core como en las aplicaciones generadas) sea más consistente de ahora en adelante.
Aquellos a los que molestaba el caso especial del nombre de archivo application.rb se alegrarán de saber que se ha cambiado a application_controller.rb. Hay más información aquí y aquí . commit
Con Rails 2.3 se introducirá la noción del default scopes : similares a los named scopes, pero que se aplican a todos los scopes o métodos find dentro de la clase. Por ejemplo, podemos escribir default_scope :order => 'name ASC' y en culauqie rmomento en que se accedan a registro de esa clase, serán recuperados ordenados por nombre (a no ser, claro está, que se indique otra opción) commit
Muchos programadores han adoptado la noción de usar try() a la hora de lanzar operaciones en objetos – he aquí el post en el blog de Chris Wanstrath que lo presenta. Esto es especialmente útil en vistas donde uno puede evitar los chequeos de nil escribiendo código como< %= @person.try(:name) %>. Pues bien, ahora está incluido dentro de Rails. commit
También en el terreno del azúcar sintáctico aparece Enumerable#none? para comprobar que ningno de los elementos cumplen con el bloque proporcionado. commit
El método render se ha ido haciendo más listo conforme pasan los años, y lo será aún más en la 2.3. Si tenemos un objeto o una colección y los nombres conciden, ahora podemos hacer tan sólo < % render @article %> o < % render @articles %> y todo funcionará. Ryan Daigle ha escrito algunos ejemples de esto. commit
En el mismo orden de cosas, en 2.3 render_component ha pasado de “a extinguir” a “inexistente”. Si es necesario, aún podemos instalar el plugin . commit
El helper autolink se ha refactorizado para hacerlo un poco menos complicado y más intuitivo. commit commit
Ha habido un arreglo para una fuga de memoria relacionada con el soporte de multithreading y los tags de assets, que podría perjudicar a sites que estuvieran referenciando muchas imágenes externas. Aaron Batalion ha contribuido la solución a este problema, así como un blog explicando el problema. commit and commit
Por último, merece la pena mencionar que ha surgido algo de controversia alrededor de un cambio hecho al código 2.2 hace cinco meses – la adición de Array#second a Array#tenth como aliases de Array#[1] a Array#[9]. Sin tomar partido en la controversia, notaremos que el cambio más reciente en edge ha reducido el soporte sólo de Array#second a Array#fifth – y con el ahorro ahora se ha podido implementar Array#forty-two. commit
A couple of months ago I bought a Mac mini to act as Media Center. The mini is connected to a plasma TV and also to my music stereo, so it makes a lot of sense to have my iTunes library there. But it’s not my primary machine, and connecting my iPhone and iPods there is not the best of the ideas because, you know, it’s not exactly a desktop.
So, the best and most comfortable way to manage my iTunes library, sync my iPods and add new songs is doing it from my MacBook Pro. But sometimes the lid is just closed or the laptop is inside my backpack, so it’d be nice to have all the music it has also copied in my always-on Mac mini. Clearly, both iTunes libraries have to be synchronized. And for manageability’s sake, better be it one-way sync (from MacBook Pro to Mac mini) than two-way.
After doing a bit of google research turns out the best and simplest solution is using the UNIX rsync utility included in Mac OS X. rsync does incremental copies remotely, it’s easy to automate, and the incremental copying is so fine-grained that it’s even capable of just synchronizing the part of your files that has changed and not the actual whole file.
This is the process I’ve followed to sync my MacBook Pro iTunes library with my Mac mini:
Now configure your primary computer to use rsync. In my case this is my MacBook Pro. Go there, and perform the following steps to write a small script you can launch every time you want to remotely update your destination computer iTunes library with the latests changes you’ve done in your primary computer:
The --archive option tells rsync to use a combination of useful syncing options (recursive, copy symlinks as symlinks, preserve permissions, preserve times, preserve group, preserve owner and omit directories when preserving times), --verbose adds more logging, --rsh=ssh tells it to use ssh to establish the connection and --delete to delete anything in the destination computer that’s not in the primary computer (this way we’re making sure no differences remain between the two iTunes libraries).
Also Do not remember to change your primary computer’s source directory to the one you’re actually using (mine is showing my username), and put the destination computer’s name instead of DestinationComputerName followed by <coed>.local (for example, in my case, it’d be Soyuz.local)
The first time you do it it’ll copy the whole library. The process will take more or less time depending on y