Posts Tagged ‘Ruby’

An elegant way to log with a Ruby block

Saturday, January 2nd, 2010

Imagine you created a generator much like Rails. It creates a series of directories and copy a set of files to a specific location. Some things may fail, and you need a nice way to show what’s going on behind the scenes.

I was browsing some code on GitHub and found an elegant approach to this problem.


module Glue
  module Generator
    extend self
    extend Glue::Helper

    def generate!(options={})
      templates = File.expand_path(File.dirname(__FILE__) + "/../../templates")
      output = File.expand_path(options[:path])

      # create root directory
      run "creating #{Colorize.yellow(output, :style => :underscore)} directory" do
        FileUtils.mkdir_p(output)
      end

      # create javascripts directory
      run %(creating #{Colorize.yellow("public/javascripts")} directory) do
        FileUtils.mkdir_p File.join(output, "public/javascripts")
      end

      # create images directory
      run %(creating #{Colorize.yellow("public/images")} directory) do
        FileUtils.mkdir_p File.join(output, "public/images")
      end

      # create views directory
      run %(creating #{Colorize.yellow("views/layouts")} directory) do
        FileUtils.mkdir_p File.join(output, "views/layouts")
      end
    end
  end
end

module Glue
  module Helper
    def run(message, &block)
      $stdout << "\n#{message}... "

      begin
        yield
        $stdout << Colorize.green("done!")
      rescue Exception => e
        $stdout << Colorize.red("error ~ #{e.message}")
      end
    end
  end
end

This code does a few interesting things:

  • the “run” method is defined inside a helper module. It begins by receiving a message (what are you doing right now?) and a block. It starts by giving control to the caller with a yield (now the execution inside the “run” method is halted). So the block passed to the run method is now executed. This block is actually the lines you see above between “run … / end”;
  • So in this block you can “do your thing”. For example, create a directory, request some info from a remote API, or whatever;
  • When the block is finished running, the lines after yield (in the “run” method) are executed. If no exception is raised a Ok message is printed, otherwise we’ll see what went wrong with the specific exception message.

This is very cool. You can now execute failure-prone tasks in a very elegant way, and with a really nice syntax :)

This code was created by Nando Vieira in an interesting project called Glue, which is a simple static site generator for Ruby that uses Haml, Sass and Textile/Markdown. The documentation is here.

You can see the code samples above, here and here.

Trânsito Não! Um experimento com Twitter, Trânsito e Ruby on Rails

Sunday, April 26th, 2009

O Twitter se tornou uma grande ferramenta para interação social, já até ameaçando o conteúdo oferecido em blogs.

Indo ainda mais longe, alguns já falam que não importa mais quantos seguidores você tenha no Twitter, mas que a pessoa com maior autoridade é aquela com o maior número de mensagens “retweetadas”, mostrando então que o que esta pessoa escreve é conteúdo bom e merece ser repassado a todos.

O projeto Trânsito Não! é um experimento social com Twitter e um assunto que deixa todo mundo fora de si: o trânsito. Este website conta tweets enviados como idéias e/ou votos, gerando um espaço público de discussão sobre um dos problemas mais urgentes destes dias.

Este projeto é direcionado a todo o Brasil, só que mais especialmente aquelas pessoas que vivem na Grande São Paulo, uma região com cerca de 17 milhões de habitantes que experimentam um dos maiores volumes de tráfego de veículos do mundo.

Usei Ruby on Rails para construir este site. Este framework web oferece grande produtividade ao desenvolvedor. Se você ainda não assistiu, não deixe de ver este vídeo que mostra a criação de um blog em apenas 15 minutos usando Ruby on Rails.

O sistema de votação funciona assim: você envia um tweet (no Twitter) com uma idéia ou solução para resolver o problema do trânsito. Esta idéia vira então uma “idéia” dentro do Trânsito Não! Cada retweet da sua idéia, vira um voto. Então quanto mais a sua idéia se espalhar no Twitter, mais votos ela recebe no site. Os tweets são obtidos do Twitter através de uma API que é lida a cada minuto. As idéias ou votos são adicionados ao banco de dados, e as páginas são geradas novamente.

Você pode me encontrar em meu blog, Twitter, ou por e-mail.

Transito Não! An experiment with Twitter, Traffic Jams and Ruby on Rails

Sunday, April 26th, 2009

Twitter has become a great tool for social interaction, and it’s also gaining more authority than content in blogs.

Going even further, some people say it doesn’t matter how many followers you have on Twitter, but instead what matters is how many times your tweets get forwarded by those following you, showing that this person writes more valuable content, which deserves to be sent over to other people.

The project Trânsito Não! (which stands for “No To Traffic!”) is a social experiment with Twitter and a subject that gets everyone mad: the traffic jams. This web app cast tweets as ideas and/or votes, generating a public web space to debate on one of the most urgent problems of these days.

This project is aimed at the Brazilian people, specially those people living in the greater area of Sao Paulo, a region with about 17 million people experiencing one of the biggest car traffics in the world.

I developed this website with Ruby on Rails. This web framework offers great productivity to the developer. If you haven’t the chance yet, don’t miss this video showing a complete web blog written in only 15 minutes using Ruby on Rails.

The voting works like this: you tweet some idea or solution for the traffic problems, followed by the hashtag #transitonao. This tweet becomes a “idea” on TransitoNao website. If your tweet gets retweeded X times, these X times become votes for your idea. So the longer your idea spreads, the more votes you get. New tweets are read from the Twitter API every minute, being added to the database, and the pages being also refreshed (using page caching).

You can find me on my blog, Twitter, or at my personal email.

Scaling Rails

Friday, February 6th, 2009

Gregg Pollack and New Relic just launched a Screencast series on Scaling Rails. And, it’s free! :)

“Scaling Rails Screencast Series” produced by Gregg Pollack and supported by New Relic.

“Learn everything you need to know about Scaling your Rails app through 13 informative Screencasts produced by Gregg Pollack with the support of New Relic. In the next few weeks we’re going to bring you 13 educational videos, teaching you just about everything you need to know to create a Rails application that can scale.”

Topics covered:

Which methods in Ruby should contain a bang sign?

Sunday, February 1st, 2009

I always thought the bang sign (!) in Ruby methods were meant to say: “I’m destructive, I’ll change your object”. Like this:


def do_something
end

def do_something!
end

Now I know better. Actually the bang sign (!) is only meant to give you and other developers a warning, like “I’m more dangerous than the other version, the non-bang one.”

Which methods should have a bang sign?

Matz says, on January 28, 2009 (EST):

The bang (!) does not mean “destructive” nor lack of it mean non destructive either. The bang sign means “the bang version is more dangerous than its non bang counterpart; handle with care”. Since Ruby has a lot of “destructive” methods, if bang signs follow your opinion, every Ruby program would be full of bangs, thus ugly.

And I (David A. Black) say:

So please stop writing bang methods that have no non-bang equivalent! The bang in isolation literally means nothing. It’s purely ornamental, and dilutes the conventional usage (see above) to the point where it’s
unrecognizable and pointless.

(Exception: things like Builder, where the bang/non-bang distinction is completely redefined, and documented as having been redefined, for the sake of domain-specific semantics.)

Source: this comment.