Ruby Gems error: uninitialized constant Gem::GemRunner

Here i am trying to install Ruby on Rails for a friend, I got this error after installing ruby gems (rubygems-1.3.1.tgz), whenever i tried to use the command it exited with this error message:

uninitialized constant Gem::GemRunner

So i had to add a line of code to the file /usr/bin/gem, the line was require 'rubygems/gem_runner'

Enjoy.

Read third party HTML using Ruby on Rails and Hpricot

A few weeks ago, mi Distributed Systems class profesor asked us to implement some sort of Web Service that gave Currency Rates information in XML format. This looked pretty easy, but all went wrong when he asked us to read the HTML from a bank’s web site and retrieve the information from there.
The idea then was to read that HTML code from a reliable site, transform it and make it available for us to download or use. Looking for a free web service that presented this information and using it wouldnt have been as easy as it was for me to use Hpricot. So here is the code I wrote, I just changed the url from where i fetched the information, because I don’t know if it is legal to do that :D.

First there is the model CurrencyService
currency_service.rb
require ‘open-uri’
require ‘hpricot’

class CurrencyService “”},
{:CUR_CODE => “USD”, :MEX_EQV => get_data(”#FIX_DATA”).gsub(/ /,”).chomp},
{:CURRENCY_EQV => “”},
{:CUR_CODE => “EUR”, :MEX_EQV => get_data(”#EURO_DATA”).gsub(/ /,”).chomp},
{:CURRENCY_EQV => “”},
{:CUR_CODE => “YEN”, :MEX_EQV => get_data(”#YEN_DATA”).gsub(/ /,”).chomp},
{:CURRENCY_EQV => “”},
{:CUR_CODE => “CAN”, :MEX_EQV => get_data(”#LIBRA_DATA”).gsub(/ /,”).chomp}
}.to_xml
end

end

And then the controller

curency_service_controller.rb
class CurrencyServiceController “text/xml”,
:filename => “currencies.xml” )
end

end

Enjoy

Problemas con MusicBrainz en Amarok( Fingerprinting of .mp3 files is not supported )

Llevo algun tiempo usando Amarok en mi Linux Ubuntu para escuchar y administrar mi música. Vi que tiene como “feature” llenar los “tags” de tu archivo por medio de MusicBrainz, sin embargo me presento este molesto error cuando intete usar dicha opción:

Tunepimp (MusicBrainz tagging library ) returned the following error:
“Fingerprinting of .mp3 files is not supported.”

La causa de este error es la falta de la librería libtunepimp5-mp3, así que si usas Ubuntu simplemente corre:

$ sudo apt-get install libtunepimp5-mp3

Reinicia tu Amarok y listo, con esto debe quedar funcional.

[Ruby on Rails] Custom search with act_as_seekable gem/plugin

http://github.com/innetra/acts_as_seekable
A common problem most of us have when creating an application is adding search methods. Some times we need to allow users to perform a search involving order paramaters, filter and a free text input for keywords or person name in case you are perfoming people search.
Rails it self provided us with some cool tools to do this, named scopes are very usefull since you can chain them to get better results, a good example would be Person.doctor.retired returning a collection of Retired Doctors (if we got those named_scopes defined).
So a few days ago I created a small plugin that adds a “seek” method to all the models you need. This seek method will recieve a hash as parameter, in this hash should look like this:
{:filter => ‘named_scope_name_for_filter’, :search => ‘Text to search’, :order => ‘column ORDER’ }

Here is a small example:
db/migrate/XXXXXXXX_create_people.rb

class CreatePeople < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.string :name
t.integer :age
t.boolean :retired
t.string :profession
t.timestamps
end
end
def self.down
drop_table :people
end
end

app/models/person.rb
class Person < ActiveRecord::Base
acts_as_seekable :paginate => true
named_scope :doctor, :conditions => {:profession => 'Doctor'}
named_scope :retired, :conditions => {:retired => true}
named_scope :elder, :conditions => {:age => 70..200}
end

app/controllers/people_controller.rb
class PeopleController < ActionController::Base
def index
@people = Person.seek(params)
end
end

The plugin/gem can be found at http://github.com/innetra/acts_as_seekable.
A better example can be found at http://github.com/gusortiz/acts_as_seekable_example
clone it, test it, do whatever you want with it.

Enjoy
Leave comments please, that way I know I’m not talking to the wall. :O

Ruby: Convertir Números en Palabras (Cantidad con Letra)

Cierto día en el trabajo nos pusimos a hacer un pequeño gem que le hace un override a la clase Numeric de Ruby, agregando un método de instancia to_words que entrega el número en texto. El número puede estar entre 0 y 9 quintillones (como si realmente necesitaras esta cantidad :D ). Esta hecho para que lo escriba en español de la siguiente forma:
$ irb(main):001:0> require 'rubygems'
$ => true
$ irb(main):002:0> require 'number_to_words'
$ => true
$ irb(main):003:0> 5678.to_words
$ => "cinco mil seiscientos setenta y ocho"

Y para que te sirva para un cheque, osea para uso monetario….

$ irb(main) :004:0> number = 4567.90
$ => 4567.9
$ irb(main):005:0> number.to_words.capitalize << " pesos " << (number.to_s.split(".")[1] || 0).rjust(2,'0')<< "/100 M.N."
$ => "Cuatro mil quinientos sesenta y siete pesos 09/100 M.N."

Hasta el momento nos ha funcionado a la perfección.
Para instalarlo y usarlo hechenle un ojo al sitio de github http://github.com/innetra/number_to_words/tree/master.

Si le encuentran defectos, errores o se les ocurre una mejora dejenme saber para ver si se incluye. Espero les sirva. Saludos.
Recommend Me

auto_complete en Ruby on Rails

Esto solía ser nativo de rails en las primeras versiones, sin embargo, a partir de la 2.0 si mal no recuerdo, fue extraido a un plugin. Este plugin esta muy bueno para auto completar text_fields en formularios.
Para usarlo primero hay que instalarlo, asi que desde la carpeta vendor/plugins de nuestra aplicación rails:
$ git clone git://github.com/rails/auto_complete.git
$ rm -rf auto_complete/.git
O bien desde la carpeta root de tu proyecto Rails.
$ ./srcipt/plugin install git://github.com/rails/auto_complete.git

Para ver buenos ejemplos de como usar este plugin recomiendo ver el capítulo 102 en Railscasts.com y el ejemplo que D.H.H. puso aqui http://github.com/rails/auto_complete/tree/master

Ahi lo tienen.
Comentarios, preguntas, dudas e insultos son bienvenidos, dejen un mensaje.
Recommend Me

Sending mail smtp gmail, with attachment using Ruby on Rails: ActionMailer

Ruby on rails has a native class to send email. It may look easy but it can get confusing when you have to configure your rails app to manage this.
All the configuration must be in the environment.rb file or in any specific environment file ( development.rb, production.rb, test.rb), however I sugest using environmet.rb so you won’t have to repeat configuration.

All the information on configuration is at http://api.rubyonrails.org but here is an example using gmail.

config/environment.rb
config.action_mailer.delivery_method = :smtp

# I do care if the mailer can't send
config.action_mailer.raise_delivery_errors = true

# Include your app's configuration here:
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => "587",
:domain => "my_app_domain", #Example: blog.local
:authentication => :plain,
:user_name => "my.gmail.account",
:password => "th1s1s4l33tpwd!"
}

That is all the configuration to send the mail, now you need to create your mailer.
$ script/generate mailer my_mailer

Write all the logic of this mailer on the “model” my_mailer.rb, here is an example that also sends an attachment, I asume that you have a user model or a person model, this model should have a field name and email:

app/models/my_mailer.rb
class MyMailer < ActionMailer::Base

def email(recipient)
recipients recipient.email
from "my.gmail.account@gmail.com"
subject "This is a test mail"
body :user => recipient # Im sending the recipient object as a local variable in a partial, but you will access it as an instance variable

@file_name = "#{RAILS_ROOT}/public/attachment.txt"
create_attachment
attachment :content_type => "text/plain",
:filename => "Some useless attachment",
:body => File.read(@file_name)
delete_attachment_file
end

protected
def create_attachment
attachment = File.new(@file_name, 'w')
attachment.puts "I am a useless text file"
attachment.puts " C(0_0)D "
attachment.close
end

def delete_attachment_file
File.delete(@file_name)
end
end

Now let’s make a view for the mail layout. This view will define the body or content of your mail.
So now you need to create a file named email.erb this is because our method that sends the mail is named email, so this basically works as the views for the controller actions. Create your file under views/my_mailer. Here is an example that uses the local variable user that I send from the email method.

app/views/my_mailer/email.erb

Hello . I have an attachment for you :)

Ok now you have almost everything done, but we still have to call our email method. This is done using a dynamic method deliver_my_method_name(param_1, param_2, …, param_n)

This is an example of this dynamic method called from the person model.

app/models/person.rb
class Person < ActiveRecord::Base
def send_email
MyMailer.deliver_email(self) # I am sending the person as a parameter.
end
end

One last thing, to send email using accounts that need tsl like gmail you need some libraries that will give you extra methods. What i did to solve this was to create a lib file in my Rails application under the lib directory ( I know this is obvious but i have to be specific :D ). This is the code of that file, I found this code googling and I just copied it into my app, it works for me and I hope it’ll work for you:

lib/smtp_tsl.rb
require "openssl"
require "net/smtp"

Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
if RUBY_VERSION == "1.8.7"
check_auth_args user, secret if user or secret
else
check_auth_args user, secret, authtype if user or secret
end

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout
#@socket.debug_output = STDERR #@debug_output

check_response(critical { recv_response() })
do_helo(helodomain)

if starttls
raise 'openssl library not installed' unless defined?(OpenSSL)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
#@socket.debug_output = STDERR #@debug_output
do_helo(helodomain)
end

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS') rescue return false
return true
end

def quit
begin
getok('QUIT')
rescue EOFError, OpenSSL::SSL::SSLError
end
end
end

Enjoy. Leave me a comment if you see anything funny, annoying, cool or just to say hello.
Recommend Me

Pruebas con Ruby on Rails… para novatos.

Ruby on Rails viene con un conjunto de herramientas bastante útiles para realizar pruebas.
Para poder empezar a probar necesitas seguir estos pasos:

  1. Primero debes crear la base de datos de prueba, por default estas en el ambiente de desarrollo y no necesariamente quieres cambiarte de ambiente cada que vas a hacer pruebas, asi que podrías hacerlo de esta manera: $ rake db:create RAILS_ENV=test
  2. Una vez creada, necesitas hacerle las migraciones: $ rake db:migrate RAILS_ENV=test

Existen mejores métodos de hacer esto, y muchas cosas más. Para conseguir mas datos sobre las pruebas revisa esta guía dando click aqui, ahi encontraras mucha más información.

Sugiero el uso de autotest, para hacer el proceso de pruebas más rápido y fácil, lo que autotest hace es correr las pruebas en segundo plano cada que detecta un cambio en tus archivos de test.
Para instalar autotest solo teclea esto en tu terminal:
$ gem install ZenTest
Y para ponerlo a probar:
$ autotest - -rails

En este sitio hay un screencast de autotest http://nubyonrails.com/articles/autotest-rails existe también un railscast en railscasts.com el número 11 para ser exactos, en el que se hace un refactoring y utiliza autotest para realizar sus pruebas.

Ahí lo tienen.
Recommend Me

How to… Rails Testing for noobies

Ruby on Rails comes with very nice testing tools. Use them!
In order to get your test working follow the next steps:

  1. First create and set up your testing database, remember that by default you are working under a development environmet so.. if you dont want to lose this configuration, and still test on the same computer you are developing just specify that you will run db:create rake task for test env just like this: $ rake db:create RAILS_ENV=test
  2. After your database is created run all migrations using the same “hack”: $ rake db:migrate RAILS_ENV=test

There are better ways to this, remember this is just a spank on your but to get you started.
For more information refer to this guide by clicking here, there you will find all you need to test like a pro.

I sugest you use the autotest gem to make it easier for you to test, specially on code refactorings.
Install auto test by running:
$ gem install ZenTest
Use it by running:
$ autotest - -rails

Check this site out for a screencast on autotest http://nubyonrails.com/articles/autotest-rails theres also a cool railscast for this topic on railscasts.com look for the 11th one.
Enjoy.
Recommend Me

Problemas instalando el mysql gem en Ubuntu

La situacion es que actualizaste tu Ruby on Rails, o instalaste la nueva versión y te diste cuenta de que necesita el gem de mysql instalado para funcionar. Entonces abriste tu constola y escribiste:
$ sudo gem install mysql.
Pero entonces obtuviste un bonito error:

ERROR: While executing gem … (RuntimeError)
ERROR: Failed to build gem native extension.
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.7 for inspection.

El problema está en que el gem de mysql necesita el paquete de desarrollo de mysql para compilar y asi poder instalarse, asi que sólo debes instalarlo primero:
$ sudo apt-get install libmysqlclient15-dev
Ya que lo tienes vuelve a intentar obtener el gem:
$ sudo gem install mysql.
Y listo ya quedo. Ahora puede pasar que el gem no pueda instalarse aun después de esto debido a que no hay espacio suficiente en la carpeta /tmp para escibir, si te pasa esto, reinicia para que se libere el
espacio que necesitas sin eliminar nada que puedas necesitar, vuelves a intentar y ya.

Ahí lo tienen.
Recommend Me

Problems installing mysql gem Ubuntu

Well here’s the deal, after updating Ruby on Rails you realized it actually needs the mysql gem installed to work. So you went to your console and typed:
$ sudo gem install mysql.
But then you got some nice error:

ERROR: While executing gem … (RuntimeError)
ERROR: Failed to build gem native extension.
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.7 for inspection.

Well the thing is that this gem needs the dev packages to compile and install so you got to install the mysql dev library:
$ sudo apt-get install libmysqlclient15-dev
Now lets go back to our gem installation:
$ sudo gem install mysql.
There you go, your mysql gem is now installed properly.
Enjoy.
Recommend Me

Guia completa de Ruby on Rails para principiantes

Apoco se la creyeron que les iba a escribir todo eso aqui.. ja ja.
Mejor los mando por el buen camino porque esas guías ya están hechas:
http://guides.rubyonrails.org/ Ahi encuentran todo lo necesario para empezar de cero. Ya que esten mas preparados, dense una vuelta por http://railscasts.com donde Ryan Bates los proveera de un puño de videos que explican un montón de cosas interesantes, tips y otros datos más avanzados.
Ahí lo tienen.
Recommend Me

Ruby on Rails getting started full guide

What!? You expect me to write a full guide to this?.
Nah, I better point out the right direction: http://guides.rubyonrails.org/ is the place to go. And after that if you want to go more advanced and see some cool tips pay a visit to our friend Ryan Bates at http://railscasts.com.
Enjoy.
Recommend Me

Follow

Get every new post delivered to your Inbox.