RSS

Method dispatch in Ruby

3 Comments | This entry was posted on Dec 15 2009

pomegranate

Some days ago I was asked how the dispatcher works in ruby and I was caught in surprise I didn’t know how to explain the method dispatching in the language we love (Ruby). That question was kept still in my mind for a few days but while listening to some workmates discussing about singleton classes in ruby the answer came to my mind in a blink of eyes reminding me from a university class which I had a long time ago about how method dispatching works in dynamic languages like Ruby.

So with that information in mind and some googling to confirm it I came out with a simple explanation of how the dispatching works in Ruby and decided it’s worth sharing you.

Essentially for each method call in ruby, the language interpreter checks in the inheritance hierarchy of the classes of the receiver (in our case “my_string“) to determine which method should be executed.

An example:

  my_string = Hash.new # => {}
  my_string.size  # => 0

The code above is pretty simple but what’s important is happening beneath of it. The language interpreter is assigning the variable “my_string” with an instance of the Hash class then it’s calling the method “size”.

The Hash class is where our interpreter will start searching for the “size” method, if the interpreter doesn’t find the method in the Hash class, it’ll continue to search in the Hash parent class, which in our case (Ruby) is the topmost class . It can be the case the interpreter don’t find the method “size”, so it’ll throw a “method missing” exception. In our example, the Hash class contains the “size” method and successfully returns.

If you want to know how MRI’s (Matz’s Ruby Interpreter) implements method dispatch, I recommend you to take a look in this blog post by Patrick Farley, where he explains the Ruby source code responsible for handling method dispatch.

For even further information on this matter there is this huge and excelent post from Russ Olsen, author of the book Design Patterns in Ruby.

How to Run Just one Test Method from your Terminal

0 Comments | This entry was posted on Oct 01 2008

Many times I found myself running all tests just after modifying just one test method. Depending on the size of your project and its test ratio, it can be a very boring waiting for it to finish.

It can be even worse: Imagine you have other tests failing. How can you improve your productivity ?  Just use the “-n method_name” parameter for the method you want to test.

ruby path_to_your_test_case -n method_you_want_to_test

A real example, I want to test the “test_should_do_stuff” method inside my “stuff_controller_test.rb”:

ruby test/functional/stuff_controller_test.rb -n test_should_do_stuff

Worth remember that stills load your fixtures and preforms setup, it only won’t execute the other test methods.

RailsConf Europe 2008 – Primeiro Dia

2 Comments | This entry was posted on Sep 03 2008

Ontem foi o Tutorials`s Day da RailsConf, mas só hoje que começou oficialmente a RailsConf Europe. Este ano tendo a presença do criador do framework Rails, (David Heinemeier Hansson) para apresentar o Keynote de kick-off da conferência.

No keynote, David falou sobre código legado. A primeira parte da palestra teve um tom mais filosófico, que tem sido (em minha opinião) uma presença cada vez mais constante nas apresentações do David. Ele comentou sobre a importância de termos código legado, que segundo ele, um bom programador é um bom programador se ele tiver escrito bastante código legado. É impossível escrever código que não se torne legado, por isso David defende que código legado deve ser mudado lentamente, sempre que for preciso corrigir algum bug ou implementar uma nova funcionalidade em um código legado, você deve aproveitar a oportunidade para deixar o código melhor e mais bonito. Durante a apresentação ele mostrou exemplos práticos de como refator código legado. O legal foi que ele mostrou isso, usando o código do Basecamp, que é a primeira aplicação feita em Rails, logo código mais legado que isso não tem heheh. Ele comentou sobre a importância de saber onde colocar as coisas em sua aplicação, dando exemplos do que tinha no Basecamp, como um Global Controller, que agregava muitos métodos que só foram parar lá por não saber onde colocar.

Logo em seguida, foi o break e aproveitei pra conhecer pessoalmente o Michael Koziarski que é um dos membros do core team do Rails. Ele é um cara bastante acessível e conversamos sobre o RailsSummit no Brasil. Ele disse que adoraria participar do RailsSummit, mas que tem viajado demais e não iria poder comparecer.

Após o break, escolhi ir na palestra “Hacking the mid-end: Unobtrusive Scripting and advanced UI techniques in Rails” apresentada pelo Michael Bleigh e Chris Selmer, ambos da Intridea. Eles apresentaram, em dois casos de uso, como usar Jquery e comportamento lowpro para manter separados comportamento (funcionamento) e markup de uma aplicação. Basicamente, os dois exemplos trataram de garantir o funcionamento da aplicação com e sem javascript, sem colocar lógica nos views.

Em seguida, assisti a palestra “Rails Software Metrics” feita Roderick Van Domburg da Nedforce, uma empresa holandesa de solucões Rails. Foi apresentado um conjunto de ferramentas para analisar a sua aplicação em termos de métricas de software. Flog, que é uma gem para auxiliar refactoring, falu do Rcov e seu plugin para rails, do Heckle que parece bem legal, pois ele além de analisar a cobertura de testes em sua aplicação, também altera o código dinamicamente. Lembro de ter visto algo parecido em uma palestra chamada “Machucando seu código” que o Fábio Akita disponibilizou traduzida em seu blog. Terminou a palestra comentando sobre o metrics_fu, que são um conjunto de tarefas Rake para usar com o software de integração CruiseControl.rb. Fiquei surpreso com a quantidade de pessoas que disseram usar CruiseControl, assim que possível vou dar uma atenção a isso. É claro que todas essas técnicas de medição de software não valem nada se você não definir metas e procedimentos para analisar elas, caso contrário, serão somente números soltos.

DHH e eu

Após o almoço, assisti “Intellectual Scalability – Solving a large problem with multiple  cooperating rails apps” dada por Frederick Cheung e Paul Butcher, ambos da Texperts. Apresentaram um caso de uso real enfretado por eles na Texperts, onde eles precisaram encontrar uma solução escalável para uma aplicação que iria crescer muito.  A solução (muito semelhante a usar Rails Engines) consistiu em dividir a funcionalidade entre diveras pequenas aplicações. Certo, mas como eles fizeram isso ? Eles mostraram com uma aplicação bem simples o funcionamento do “framework” próprio criado por eles para encarar o problema. Foi uma palestra bem técnica, com bastante código sendo feito ao vivo. Gostei bastante.

Em seguida, não havia nenhum assunto que me interasse e acabei assistindo “Scaffolding an application from schema.rb” dada por Tomaso Minelli. O Tomaso é Italiano e tinha um sotaque carregado, que deixou a palestra um tanto “arrastada”. Foi uma palestra bem iniciante, onde ele apresentous as principais soluções de scaffolding do mercado e apresentou sua própria solucação de scaffolding que é apartir do schema.rb. Ele basicamente redefiniu o método ActiveRecord::Schema.define.

A última palestra o dia foi “Stories on a cloud – Distributed browser testing with selenium” dada pelo Martin Sadler. Com o javascript cada vez mais sendo usado hoje em dia, é preciso termos como garantir que nossas aplicações funcionem bem independente de navegador ou sistema operacional. Ele mostrou o Webrat e RSpec Stories, e logo em seguida mostrou como unir o melhor de cada um atrelando a um servidor Selenium distribuído em vários computadores usando um sistema de mensagens para executar os testes em cada computador. Foi bem bacana, só faltou um exemplo ao vivo pra me convencer.

No momento que escrevo este post, Jeremy Kemper, outro membro do core team, está dando um keynote de encerramento. Se for legal, posto o que ele falou mais tarde.

=D

Writing Opinionated Software

3 Comments | This entry was posted on Jul 28 2008

Sometimes I got myself thinking what makes a software have its own opinion and be considered “optioned software”. Would it be related to the language philosophy or to the programmer itself, or both of them?

People usually say Rails is a good example of optioned software. I can say I take part of the same opinion, but I’d like to take this point a little more further by not emphasizing only the software, but the programmer and how its culture could be incorporated (and not avoided) in the software it produces.

Out there, in the software market, when hiring people, companies usually claim they give plenty of room for people to innovate, share ideas and try new things and all that cool stuff we usually hear from Googles’s employees about independence and space to build your own skills and develop ideas within the job. But what we found most in the reality is the same copy & paste philosophy everywhere. The programmer usually don’t have time to try new things, because he is stuck with a pile of tedious tasks to complete and the deliverable is always behind schedule, which appears to be a endless cycle, project after project.

I believe, Ruby on Rails came to “save” the people from these kind of starving companies, which likes to hire young and “virgin” employees to mold them to the “Software Factory” style. Ruby on Rails lets the programmer surpass most of the tedious tasks, so it lets the programmer have free time to innovate in other areas of the software. It depends, of course, on the company philosophy, but when companies envise the real profit they can benefit from having a happy employee and tailoring the software for the user real needs, the companies will would like to have adopted the Ruby on Rails earlier.

Ok, but where the programmer opinion comes in ? I strongly believe by having more time to think, the programmer can not only fix issues, but can also suggest new features, test and present them very quickly and best of all, he also can earn more as people usually like to pay for what’s well done.

All in all, writing optioned software is not about yelling what’ s your favorite band, but it’s all about programming and being happy.  I am a happy programmer and you ??

[update 08-01] Thanks Soleone for your suggestion

Ultrasphinx bug?

1 Comment | This entry was posted on Jun 15 2008

It seens Ultrasphinx plugin for Ruby on Rails doesn’t know how to deal with Decimal data type from MySQL.

You can use a Decimal column for indexing, but when you need to make thecolumn sortable it comes the problem. As you know, faceting is on for numeric and date fields and to add the sortable feature to it, we need to pass a hash with

{:sortable => true}

Ok, then you run rake tasks to rebuild your configuration file and indexes and try to sort the search by the Decimal column and we got an error saying our column isn’t sortable.

You can check isn’t generating the _sortable sufix by looking the ultrasphinx configuration file. All other sortable fields have their _sortable sufix added to ti, except by the decimal field.

I’ll report it as soon as possible to Evan Weaver, the plugin’s owner, or maybe try to fix it by myself.

Updated: June, 16

I fixed by adding  ‘decimal’ => ‘float’ in the TYPE_MAP inside the fields.rb file of ultrasphinx plugin.

RELEASED – “Rails 2.1 – What`s new ?” Book

2 Comments | This entry was posted on Jun 09 2008

Book Cover

The Book Rails 2.1 – What`s new ? Made by Carlos Brando and Tapajós was released last week. It was the very first book presenting Rails 2.1 and its new features, in Portuguese, and best of all, it was released free of charge ( like free beer).

But Carlos Brando and the Brazilian rails community were very upset because most Railers of the world couldn`t read portuguese so they couldn`t rejoice the book like us. So I and other fellows, lead by Carlos Brando got together to translate the book to english, so all people could read and use it.

I`m very proud of being part of this community that made the translation and reviewed it in less than 2 days. You can download the book here or from Carlos Brando blog.

I and these guys are who made this task possible, so please thanks us and if you like our work, please recommend us in in Working With Rails:

Rafael BarbosaRecommend
Made Introduction and chapter 1

Caike Souza – Twitter: @caike
Made Chapter 2

Pedro Pimentel (Myself) – Recommend
Made Chapters 3-8 and 10-13

Abraão CoelhoRecommend
Made Chapter 9

Ricardo S YasudaRecommend
Made Chapter 14

And last, but least, don`t forget to thanks and recommends the authors if you haven`t did yet.

Recommend Carlos Brando

Recommend Marcos Tapajos

More information about the original book can be found in Carlos Brando blog.

Download the book here

Internacionalizando uma aplicação rails

4 Comments | This entry was posted on Jan 22 2008

Internacionalizar uma aplicação exige um planejamento dada as diversas opções de ferramentas existens. Em Ruby on Rails, onde a idéia era não ter suporte oficial ao i18n(internacionalização) temos algumas ferramentas para tornar nossa aplicação multi-língua. Neste contexto, existe uma ferramenta chamada
gettext, que segundo definição da wikipedia:

é uma biblioteca do Projeto GNU que faz a internacionalização de
softwares, ou seja, a escrita de multiplas línguas em
softwares

Este tutorial tenta esclarecer o desenvolvedor ruby on rails que tem
dificuldade de internacionalizar sua aplicação utilizando o gettext.

Inicialmente vamos instalar a gem gettext em nosso sistema.

sudo gem install
gettext

Seleciona a versão de acordo com o seu sistema. (Este tutorial foi realizado
usando Ubuntu Linux, caso esteja no windows, basta retirar o comando
sudo).

Para o correto
funcionamento do gettext e deste tutorial devemos nos certificar que
todas strings e conexões ao banco de dados estão sendo
realizadas usando encoding UTF-8.

Depois de nos certificar de usarmos o encoding adequado agora vamos preparar a aplicação para
internacionalização de fato e para isso vamos adicionar algumas tarefas
no Rakefile da aplicação. Opcionalmente você pode adicionar estas
tarefas dentro da sua biblioteca de tarefas em lib/tasks. Abra seu
Rakefile e vamos adicionar as seguintes tarefas adequando as strings
myapp de acordo com o nome de sua aplicação:

desc "Create mo-files"task :makemo do
require 'gettext/utils'
 GetText.create_mofiles(true, "po", "locale")
end
desc "Update pot/po files to match newversion."
task :updatepo do
	TEXT_DOMAIN = "myapp"
	APP_VERSION = "myapp1.1.0"
	GetText.update_pofiles(TEXT_DOMAIN,
		Dir.glob("{app,lib}/**/*.{rb,rhtml}"),
		APP_VERSION)
end

O código acima é encontrado nos manuais disponíveis dentro do site Ruby on Rails . Note que a tarefa :updatepo é a responsável por varrer a sua aplicação em busca de arquivos *.rb e *.rhtml.

O próximo passo é definir a hierarquia do gettext em nosso projeto. Vamos criar uma pasta na rails da aplicação chamada “po” e dentro dela vamos criar a seguinte hierarquia:

po
| pt_BR
| en_US
| en_UK

Para cada língua que desejamos ter, devemos criar um diretório cujo nome é seu código correspondente. Para saber mais sobre que códigos usar sugiro ler este artigo do W3C.

Agora vamos informar nosso ApplicationController que vamos internacionalizar toda nossa aplicação. Abra seu ApplicationController e vamos adicionar algumas duas linhas nele. Ressalto que altere a string myapp de acordo com o nome de sua aplicação definido anteriormente.

require 'gettext/rails'
classApplicationController < ActionController::Base
	init_gettext"myapp"
end

De agora em diante devemos adotar o seguinte método toda vez que formos inserir texto que a ser traduzido em nossa
apli
cação:

< %=_("Este texto deve ser traduzido.")%>

Para padronizar o trabalho de tradução de forma a facilitar a cooperação internacional em projetos de software livre convenciona-se que se utilize o inglês como língua base de nossas strings de texto no projeto.

Lembram das tarefas que criamos em nosso Rakefile? Agora vamos rodar a tarefa :updatepo.
Abra o terminal com a raiz em sua aplicação e use o comando:

rake updatepo

Após a varredura em busca de strings a serem traduzidas, um arquivo de nome myapp.pot será
criado dentro do diretório po. Este arquivo é um template que vai ser utilizado para todas linguagens que vamos traduzir.

Abra ele com um editor de arquivos po. Eu uso em meu Ubuntu o POEdit facilmente instalado através do gerenciador de pacotes.

Com o arquivo de template aberto em nosso editor de arquivos po, vamos salvar o arquivo como myapp.po dentro do diretório po na pasta cujo nome é o código da tradução alvo. Por exemplo, se estivermos traduzindo para o inglês do estados unidos, devemos salvar dentro da pasta en_US.

Traduzidas as strings, vamos agora “compilar” a tradução para ser usada em nossa aplicação. Com o seguinte comando em seu terminal:

rake makemo

Um novo diretório chamado locale será criado na raiz de sua aplicação contendo os arquivos compilados de
tradução.

Pronto! Sua aplicação está internacionalizada!

Para ver sua aplicação na língua nativa, acesse sua aplicação normalmente pelo browser:

http://localhost:XXXX/myapp/

onde XXXX é o número da porta de sua aplicação.

Para vermos nas demais línguas que traduzimos basta alterar o código de locale:

http://localhost:XXXX/myapp?lang=en_US

Caso tenha utilizado outros códigos, teste-os também!

Espero que seja útil.
Obrigado.