A Django site.
April 10, 2010
» Activerecord file fun

For those who doesn’t know Activerecord is a software design pattern, not only an implementation.

Sometimes you are in a middle of a rush and Mr. Murphy knocks your door. I had such case: Customer imported user emails with a misspelling, asked for help. I tried to exercise my SQL skills in a bad way, Murphy steps in. Fortunately we have tools for fixing things.

Activerecord is an approach for database access, it’s based in OOP concepts and basically maps a record as a class. Thus, you can treat each record as standard objects, this means (for the lazy) that you can do things like attribute update.

So, back on the case. I wrote a simple piece of code using Ruby on Rails AR implementation. What it does? It saves my job, filename says it all (for the es_PE speaking people). It uses the email addresses from the file to update the email column in the database for each user.

Note: This case only works for 1:1 matching situation. If the list is sorted somehow different than the records, things will go wrong. However I post it here for educational purposes. I’ve commented the code acoordingly. Enjoy and comment.


cat recon.rb
#!/usr/bin/ruby

# Imports rubygems classes and then active record
require 'rubygems'
require 'active_record'

# Let AR know who is working with!
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:host => 'localhost',
:database => 'app',
:username => 'user',
:password => 'secret'
)

# Map table as a AR class.
# Note that I had to set the table name, since my database didn't use AR naming convention, so I had to also set primary key.

class User < ActiveRecord::Base
set_table_name :user
set_primary_key :user_id
end

# Open the lucky file.
f = File.open("emails.txt")
# Update each record thanks to AR properties. Yay!
User.find(:all).each do |u|
u.update_attribute :email, f.gets.chomp
end

# Just check if it did the job.
puts "check"
uc = User.find(:all)
uc.each do |usr|
puts "#{usr.username} : #{usr.email}"
end

July 26, 2009

Antonio Ognio
gnrfan
» Renaming downloaded MP3 files with Ruby

Hi there. This post is just an excuse for doing this 3 things:

  • Creating a new post. I haven’t really posted to this blog in a while
  • Try out the Pastie embedding functionality here
  • Provide a place to look for this script later when I’ll need it

Once that has been disclaimed I just want you to know that I’m a big podcast fan and I generally and up selectively downloading MP3 files for many podcast episodes using wget. Problem is sometimes the links I copy & paste to the shell or some Bash script include query strings with many aditional parameters and the resulting filenames end up including these long query strings in them.

So, in order to rename this files I just wrote this Ruby script which I’ve just copied to /usr/bin/mp3qsrm on my Leopard partition:

I don’t do Ruby on an everyday basis like I do Python nor I have a ton of years of experience like I have with PHP so whenever I’m coding Ruby reference like this tutorial is very useful. I’ve you are a coder I think you should take Ruby for a spin. Both Ruby and Python come installed by default under OS X and it’s very easy to install on a Linux distro.

October 28, 2008

Jaime Wong
jgwong
Sueños de Azul
» Beta de Ruby 1.9 para SymbianOS

Beta de Ruby 1.9 para SymbianOS. Yes.

August 11, 2008

Cesar Villegas
slayer
Slayer_X homepage
» Conferencias: Dynamic Programming Day 2008

Si eres desarrollador web y planeas dedicarte en serio a la programación para web te recomiendo firmemente que acudas a las conferencias Dynamic Programming Day 2008 organizadas por el Grupo de Usuarios de Linux del Perú
Dynamic Programming Day 2008

La entrada es completamente gratuita y ademas se van a regalar CDs con códigos fuentes, vídeos y documentación. Se hablará de todos los lenguajes de “moda” y sobre las últimas tendencias en programación web. Asi que ya saben no se la pierdan ;)

Mas información con el programa y los detalles en la página del evento: http://www.linux.org.pe/dpd08/

April 23, 2008

Jaime Wong
jgwong
Sueños de Azul
» Ruby for SymbianOS!

Lo comentado anteriormente se está haciendo realidad. ¡Aquí la primera contribución hecha realidad para un Ruby for SymbianOS!

March 29, 2008

Jaime Wong
jgwong
Sueños de Azul
» ¿Habrá un port de Ruby para SymbianOS?

En la web de Nokia Nseries comentan sobre un port de Ruby 1.9 para SymbianOS. El port está agendado para salir en Abril 2008 (¡no falta nada!). Esa es una maravillosa noticia para los fans de Ruby como yo.

November 27, 2007

Jaime Wong
jgwong
Sueños de Azul
» Linux Day Ica 2007

El SENATI está organizando un evento llamado “Linux Day Ica,” que se llevará a cabo este Sábado 1ro de Diciembre en el Hotel Real Ica. Representando al PLUG, estaré participando como ponente; mi tema será “Desarrollo Web con Ruby on Rails” — mayormente introductorio y habrá también un taller en la tarde donde será todo práctico.

Los otros ponentes y temas son:

Antonio Ognio - Introducción a GNU/Linux
Clever Flores - Instalación de GNU/Linux
Nestor Ruiz - GNU/Linux como servidor

Los demás temas también tienen taller, así que aprovechen.

Más información: www.linuxdayica.com

November 13, 2007

Jaime Wong
jgwong
Sueños de Azul
» Twitter Habits: un script en Ruby

La mejor forma de aprender algo nuevo es aplicándolo a algo que ya sabes o te interesa. Estaba aprendiendo a usar HPricot (un gem de Ruby para procesar páginas web y hacer web scraping). Me hice un script sencillo que recoge las entradas de un usuario de Twitter y las tabula por horas.

Por ejemplo, este es el resultado para el usuario de DrMad:

    Gathering data for drmad [...........................]
    
    00 = ( 19) ******
    01 = ( 28) **********
    02 = ( 17) ******
    03 = (  5) *
    04 = (  5) *
    05 = (  2)
    06 = (  5) *
    07 = (  5) *
    08 = ( 16) *****
    09 = ( 34) ************
    10 = ( 41) **************
    11 = ( 41) **************
    12 = ( 65) ***********************
    13 = ( 28) **********
    14 = ( 20) *******
    15 = ( 23) ********
    16 = ( 26) *********
    17 = ( 38) *************
    18 = ( 24) ********
    19 = ( 20) *******
    20 = ( 25) *********
    21 = ( 13) ****
    22 = ( 27) *********
    23 = ( 24) ********
    
    Total twits: 551

No nos cabe duda que este chico no duerme.

A ver, veamos el de Jason Kottke:

    Gathering data for jkottke [..........]
    
    00 = (  0)
    01 = (  0)
    02 = (  0)
    03 = (  0)
    04 = (  0)
    05 = (  1) *
    06 = (  4) ****
    07 = (  5) *****
    08 = ( 12) ************
    09 = ( 16) ****************
    10 = ( 15) ***************
    11 = ( 16) ****************
    12 = ( 17) *****************
    13 = ( 15) ***************
    14 = ( 11) ***********
    15 = ( 11) ***********
    16 = ( 19) *******************
    17 = (  9) *********
    18 = (  6) ******
    19 = ( 11) ***********
    20 = ( 12) ************
    21 = (  6) ******
    22 = (  5) *****
    23 = (  3) ***
    
    Total twits: 195
    

¿Pude haber usado la API de Twitter? Sí. ¿Te has dado cuenta que ignoras la primera entrada? Sí. Estaba aprendiendo a usar HPricot y no tratando de hacer algo cool pero inútil. Por eso lo hace de la manera más ineficiente posible.
Oh, y no sé por qué la página de César Soplín tiene tags distintos a los demás. ¿Twitter le teme al policía de la usabilidad?

El script en cuestión lo pueden descargar de aquí: twitter_habits.rb
Requiere HPricot 0.6. Lo ejecutas así: ruby twitter_habits.rb usuario

Como siempre, si se rompe, te puedes quedar con las dos piezas.

October 20, 2007

Jaime Wong
jgwong
Sueños de Azul
» Este Domingo en el Censo, vámonos de pesca

Así es, vamos a practicar el novedoso deporte inventado por Dilbert llamado “Carpet Fishing” (Pesca de Alfombra).

¡He escrito el programa para pescar en Ruby! (*)

¡Ahora nadie tiene excusa para aburrirse!

Diversión, relax y tranquilidad en la seguridad de tu propio hogar. No malogren su hígado, sobre todo porque ni siquiera podrán salir de sus casas a comprar Milanta.

* No incluye caña de pescar, el horrible olor del pescado ni soniditos de la naturaleza.

October 2, 2007

Jaime Wong
jgwong
Sueños de Azul
» Libro gratis de Ruby on Rails

En Sitepoint están ofreciendo gratis el libro completo de Patrick Lenz, “Build your own Ruby on Rails applications” por 60 días.

September 11, 2007

Jaime Wong
jgwong
Sueños de Azul
» 10 razones para aprender Ruby

10 razones para aprender Ruby

Tags: ,

August 30, 2007

Jaime Wong
jgwong
Sueños de Azul
» Superators: creando operadores en Ruby

Superators es un gem de Ruby escrito en Ruby puro que permite crear nuevos operadores, aunque con ciertas limitaciones. Ahora es posible hacer cosas como este ejemplo de Aleks (heh, qué pequeño es el mundo):

["aleks", "bob", "monkey", "zebra"] <~ ["joseph", "xylophone"]

o se me ocurre:

status +-

para negar el valor de una variable (i.e. status = !status). Utilísimo para DSLs o proyectos muy personales. Demasiada magia no es buena.

April 26, 2007

Gustavo Picón
tabo
Hacking for fun and profit
» On Python vs Ruby

Taken from a Python up, Ruby down discussion in programming.reddit:

Ruby takes all the elegance and simplicity of Perl, and mixes it with the library support of Lisp

- foonly

Previously…

June 26, 2006

Nicolás Varcarcel
nxvl
Nikolas Valcarcel
» RubyZilla: Un navegador en 10 minutos.

Ahora que estoy comenzando con Ruby me puse a leer manuales sobre Ruby/Gtk y estuve buscando además manuales de Glade para Ruby. Buscando por la web encontre un video de como programar un web Browser en 10 minutos usando Glade y Ruby que demustra bastante bien la potencia y sencillez de este lenguaje y como apenas escribe algunas lineas de codigo.

RubyZilla