Archive for 2008
Introducing Feedbag: Feed auto-discovery Ruby library/tool
Last week, I spent some time building a good (that I liked) feed auto-discovery tool to use in Ruby for other project I'm building, rFeed. I liked CPAN's Feed::Find, and at some point I made a wrapper class to run a Perl script using such module, however, I wasn't happy by mixing it all. So, Feedbag was born:
>> require "rubygems" => true >> require "feedbag" => true >> Feedbag.find "log.damog.net" => ["http://feeds.feedburner.com/TeoremaDelCerdoInfinito", "http://log.damog.net/comments/feed/"]>> planet_feeds = Feedbag.find("planet.debian.org") [ ... ] >> planet_feeds.first(3) => ["http://planet.debian.org/rss10.xml", "http://planet.debian.org/rss20.xml", "http://planet.debian.org/atom.xml"] >>planet_feeds.size => 104 >>
It makes smart use of relative and absolute bases, hrefs, links, content types, etc. It is also a single Ruby file, so you can grab it and use it on your application. Plus, it only requires Hpricot as dependency. It can find all feeds linked on a web page, but it will return the most important at the beginning of the resulting array, so you will have the important one on the first results (see example above with Planet Debian).
Synopsis, README and a brief tutorial have been placed at axiombox.com/feedbag. You can also take a look at the git repo, hosted in GitHub.
Good looking Irb
Irb is a pain to work with… when you don't know it enough. Fortunately, it can be configured extensively enough to make your Ruby interactive sessions much smoother. Pocahontas asked me to post my Irb configuration:
# ~/.irbrc
IRB.conf[:AUTO_INDENT] = true
IRB.conf[:USE_READLINE] = true
IRB.conf[:SAVE_HISTORY] = 5000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb_history"
IRB.conf[:PROMPT_MODE] = :SIMPLE
require 'irb/completion'
require 'irb/ext/save-history'
require 'pp'
# load rubygems and wirble
require 'rubygems' rescue nil
require 'wirble'
require 'utility_belt'
# load wirble
Wirble.init
Wirble.colorize
Which makes Irb to look much much better:

But it is not only coloring the features you are getting, but also Readline support, command history saving, tab completion, libraries loaded by default, persistent history with Wirble, etc, etc. as you can see yourself on the very self-explanatory configuration file. Enjoy.
Update: I have to thank my co-worker Galin for pointing me most of these neat features.
Two Git tips
Following the Git tips being thrown on Planet Debian, here's a couple:
1. Changing into a directory that contains a repo and shows you on PS1 what branch you are standing on:
On .bashrc I have:
GITPS1='$(__git_ps1 ":%s ")'
export PS1="${GREEN}\w${RS} ${YELLOW}${GITPS1}${RS}\\$ "
2. An alias I like to use on repos that are personal for quick tracking:
[alias] ... log1 = log --pretty=oneline --abbrev-commit
I hope you like them.
High-Order Perl available for free
My friend Marco first told me on IM, then I read it on PerlBuzz. The nice High-Order Perl book by
Mark Jason Dominus is now available for free (as in free beer) at its website.
This book caught my attention a long time ago on a Barnes & Noble once, but since I had just too many book on queue, I decided not to buy it. I then read that it's actually a good book on "advanced" techniques on Perl, so my interest grew, but for random reasons I just didn't get it.
Now I have no excuses not to, and either do you
DirectoryIndex and the "perl-script" handler
Wouter Verhelst blogs about combining ScriptAlias (or a way to run CGIs) and DirectoryIndex in Apache.
Recently, developing a TinyURL clone I had a similar (not identical, though) issue.
Basically, I set SetHandler to perl-script on the "/" location, which basically means, everything accessed on a given virtual host, is affected. Because you are changing the handler for the entire location, DirectoryIndex will have no effect on it because mod_dir is the one dealing with the DirectoryIndex function, that is, using the DIR_MAGIC_TYPE handler.
To fix this you can use a mod_perl (2, I never really used 1) Fixup phase handler:
<VirtualHost *:80>
...
# some stuff
...
# PerlSections rule.
<Perl>
$Location{"/"} = {
SetHandler => 'perl-script',
# some stuff
PerlFixupHandler => 'Axiombox::Awbox::Fixup',
# some other stuff
DirectoryIndex => 'whatever.html',
};
</Perl>
</VirtualHost>
If it looks incomplete is because some other information, out of the scope of this sample, like DocumentRoot or other mod_perl directives, are hidden as the "other stuff". My Fixup.pm handler looks like this:
package Axiombox::Awbox::Fixup;
use strict;
use warnings FATAL => qw(all);
use Apache2::Const -compile => qw(DIR_MAGIC_TYPE OK DECLINED);
use Apache2::RequestRec;
sub handler {
my $r = shift;
if ($r->handler eq 'perl-script' &&
-d $r->filename &&
$r->is_initial_req)
{
$r->handler(Apache2::Const::DIR_MAGIC_TYPE);
return Apache2::Const::OK;
}
return Apache2::Const::DECLINED;
}
1;
Which is very straight-forward: If the request is set to perl-script, the requested file is a directory and if the current request is the main one, then change the handler and return to the normal flow of phases. Otherwise, decline the Fixup phase handler.
Gracias
Aunque en realidad la gente no da gracias y es un hecho meramente histórico, la celebración de thanksgivin' me hace reflexionar al respecto de a quién y por qué daría gracias.
Dicho lo anterior.
Le doy gracias a Dios por hacerme feliz. Por tener la mejor mujer del mundo, la mejor familia, los mejores amigos y una vida llena de sueños, anhelos y esperanzas. Le doy gracias a Dios por colmarme de amor, por bendecirme con una vida tan plena y completa como la que creo tener.
Book meme
- Grab the nearest book.
- Open it to page 56.
- Find the fifth sentence.
- Post the text of the sentence in your journal along with these instructions.
- Don't dig for your favorite book, the cool book, or the intellectual one: pick the CLOSEST.
"De esta triste estancia en la capital de Colombia se rescata el que pudieron ver jugar al mítico Real Madrid contra el Millonarios."
Translation: "From this sad stay in the capital of Colombia, it was worth they saw the mitical Real Madrid play Millonarios."
From Ernesto Guevara también conocido como el Che (Ernesto Guevara also known as Che), by Paco Ignacio Taibo II.
Configuración dinámica en Apache
Una de las cosas más bonitas que puedes hacer gracias a mod_perl, son las PerlSections.
Básicamente con éstas, lo que puedes hacer es definir dinámicamente directivas de configuración de Apache y hacer cosas bien interesantes. Por ejemplo, recientemente, para Planeta Linux quería tener una sola configuración de Apache para los virtual hosts que son repetitivos dada cada instancia (mx.planetalinux.org, ve.planetalinux.org, gt.planetalinux.org, etc). Precisamente lo que quiero evitar es tener que poner una interminable lista de VirtualHost's, así que lo puedo hacer con secciones en Perl (que son denotadas en cualquier archivo de configuración en Apache con <Perl> y </Perl>):
<Perl>
my $names = { cl => 'PlanetaLinuxChile', co => 'PlanetaLinuxColombia', cr => 'PlanetaLinuxCostaRica', ec => 'PlanetaLinuxEcuador', sv => 'PlanetaLinuxElSalvador', es => 'PlanetaLinuxEspana', gt => 'PlanetaLinuxGuatemala', mx => 'PlanetaLinuxMexico', ni => 'PlanetaLinuxNicaragua', pa => 'PlanetaLinuxPanama', pe => 'PlanetaLinuxPeru', ve => 'PlanetaLinuxVenezuela', debian => 'PlanetaDebian', };
Defino una referencia a hash en $names que lista contra los "TLDs" de cada instancia y con su nombre largo.
my $instancias = [keys %{$names}];
Para facilitar trabajar con las llaves, creo una referencia a un arreglo que contiene exclusivamente las llaves del hash que previamente tenía definido.
$VirtualHost{"*:80"} = [];
Como voy a definir todos mis VirtualHost's apuntando hacia "*:80", defino el valor de la llave "*:80" del hash pre-definido $VirtualHost (pre-definido por mod_perl), hacia una referencia de arreglo vacío (por el momento).
for my $pais(@{$instancias}) {
Empiezo a interar cada uno de los elementos de $instancias y asigno cada valor en la interación a $pais.
my $vhost = $pais.".planetalinux.org"; if ($pais eq 'debian') { $vhost = 'planeta.debian.net'; }
El nombre del servidor será $pais.".planetalinux.org", a menos que sea "debian", que no lleva el dominio de Planeta Linux.
my $virtualh = { SuexecUserGroup => ["planetalinux", "planetalinux"], ServerAdmin => 'planetalinux@googlegroups.com', ServerName => $vhost, DocumentRoot => "/var/www/planetalinux/".$vhost, ErrorLog => "/var/log/apache2/planetalinux_".$pais."_error", CustomLog => ["/var/log/apache2/planetalinux_".$pais."_access", "combined"], LogLevel => "info", Alias => ["/images/", "/home/planetalinux/current/www/instancias/".$pais."/images/"], Redirect => ["/rss20.xml", "http://feedproxy.google.com/".$names->{$pais}], };
Aquí defino la referencia al hash principal del virtual host. Los valores son definidos con los nombres de las directivas que utiliza Apache:
SuexecUserGroup, pues utilizamos suexec en el servidor se asigna a una referencia de arreglo anónima con dos valores, que son los dos valores que se le pasan a Apache en sus directivas regulares.ServerAdmin, es el mismo para todas las instancias, nuestra lista de correos.ServerName, es el nombre que definí previamente como$vhost.DocumentRoot, depende también de$vhostpues así lo tenemos definido en nuestro sistema de archivos.ErrorLog, caso similar aDocumentRoot.CustomLog, caso similar a ErrorLog, pero defino, igual que enSuexecUserGroup, un arreglo anónimo con los dos valores que toma este parámetro.LogLevel, igual que en Apache.Alias. Defino un alias simple.Redirect, puedo utilizar cualquier tipo de directivas,Alias,Redirect, lo que sea. En este caso, realizo la redirección de los viejos feeds"/rss20.xml"hacia la nueva URL de FeedBurner, que es ahora como manejamos los feeds en Planeta Linux. El valor que se concatena al final es el valor del hash%{$names}dada la llave$pais.
push @{$VirtualHost{"*:80"}}, $virtualh;
Agrego cada $virtualh al arreglo de VirtualHosts en "*:80". Si tuviera una IP por cada uno de los VirtualHosts, no es necesario hacer push a un arreglo, simplemente tendría que declarar las variables $VirtualHost con la IP como llave. Sin embargo, si declaro muchas veces la misma variable, como en este caso, $VirtualHost{"*:80"}, en cada interación el valor se reescribirá, es por eso que mod_perl nos ofrece definir esa variable como referecia a arreglo en donde podemos meter cuantos virtual hosts como queramos.
}
Termino el ciclo for.
</Perl>
Las posibilidades son muchas para la configuración dinámica de Apache y en secciones Perl puedes utilizar cualquier cosa, abrir tus archivos para ver otros parámetros de configuración, conectarte a bases de datos para sacar información, lo que sea.
Si te interesa ver todo el archivo de configuración, está acá, en el GitHub público de Planeta Linux.
Linux México
Con la reciente y repentina muerte de Cofradía, la comunidad de linuxeros (y demás rarezas) en México necesita más que nunca un nuevo nicho. Afortunadamente, Planeta Linux México se ha consolidado como una verdadera comunidad de linuxeros mexicanos, y tan es así que ahora somos el resultado número uno en Google y en Google México para «linux méxico».
Aunado a ésto, algunos colegas y yo hemos iniciado un simple y sencillo grupo LinkedIn de Linux en México para que todos nosotros, profesionales, desarrolladores (y usuarios también, ¿por qué no?) hagamos networking. Únanse.
Harlem and the elections
A lot has been said about the elections already. I just want to share my personal experiences about it. During the weekend, Tom invited us to his place in lower Harlem (we live upper Harlem) on 123rd St and Adam Clayton Powell Jr Ave, for Tuesday night. As Tuesday arrived, we didn't see too many people too excited about it. Living in Harlem, we were pretty used to black people supporting Obama, so getting closer and closer to the elections, we didn't feel people anxious. On Tuesday, we commuted to work and some of our co-workers got to work late because they have been standing in lines for a couple of hours to vote in polls. The whole day was about talking on how much that day was representing for the US and the world, guessing how they results were going to end up, etc.
Later at night, Greg, Phil, Raquel and I headed to Tom's place for his watch-the-results party. His fridge was full of Blue Moon beer, but he also had some Red Stripe
Since I like to go light on politics, I preferred some other American variantion, Coors Light
Vermont, Connecticut and a few other New England states were claimed by the Democrats. Matty, a friend of Tom attending the party brought US maps with the electoral votes on each one for people to color them as they were called. It was pretty fun. At some point we forgot about the maps since it was pretty clear that Obama was gonna win. But when they called him at around 11 pm (and I was starting to feel nicely drunk), the whole neighborhood and people in the streets just went completely nuts. It's something I hadn't experienced at all in my life, it was like if Mexico would have won the fútbol World Cup (which yes, it will never happen anytime soon
), but nicer. People went out to the Harlem State Office Building square were cars were honking, and a huge amount of people gathered to celebrate, play brass music, cheer "Yes We Can". Ghetto guys, white hippies, curious latinos, Africans, African Americans, Puerto Ricans, just a lot, a lot of people, all kinds of them, just a clusterfuck. They projected Obama's speech from Chicago and people went nuts. It was just, fucking amazing. The images they projected from Harlem to the outside world was in that same square we were in.
Our Flickr set for the celebration here.





