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.

Why my f***ing awesome web app doesn’ t move forward ?

4 Comments | This entry was posted on Jun 16 2009

What prevents an application, like Twitter,  of acquiring more and more users besides the geek users? Even within my circle of friends and acquaintances that work/study with IT, when I talk about I’ m a Twitter user, I need to repeat uncountable times what Twitter is about  and I usually explain to them according to what twitter advertise as their goal (Not a micro blogging tool, What are you doing?). In 90% of the cases, they say they heard about it but don’t know what´s its purpose, in other words, they don´t know how they could use twitter for their benefit. ”Why would I tell ´followers´ what I am doing ?¨ is the most asked question after  my explanation.  It means Twitter´s initial goal failed to instigate the user to create a new need, but why ?

Read more »

A recipe for Lazy Programmers

2 Comments | This entry was posted on Jun 14 2009

Fact: programmers are one of the laziest creatures on earth and when it comes to ruby programmers, like me, the problem is even worse. We don´t like to spend more than 5 minutes cooking something while we could be doing something more important like chatting with your friends on freenode.

Read more »

View sql queries in your console

2 Comments | This entry was posted on Mar 22 2009

Don’t you think it’s really irritating when, in the console, you are testing your model’s methods and everytime you need to check how each SQL query was formed you need to go to another tab to visualize the log ???

Your frustation is over. Just add the following lines in your .irbrc file:

def log_to
  ActiveRecord::Base.logger = Logger.new($stdout)
  ActiveRecord::Base.connection_pool.clear_reloadable_connections!
end

You can change the method’s name to whatever suits your needs. After that, every time you are in your application’s console you just type log_to and you’re ready to go:

>> log_to
=> []
>> MyModel.count
  SQL (1.8ms) SELECT count(*) as count_all FROM "mymodels"
=> 10

This hint I got it from Pratik Naik while doing pair programming with him at the company I work.

Qcon London 2009

1 Comment | This entry was posted on Mar 20 2009

qcon_logo_london_2009

After 4 months of no activity here (in my twitter I post more frequently), i’m posting some notes from Qcon London I attended this year.

Curiously, Qcon London began with a keynote from the scientist Tony Hoare (inventor of quicksort) that didn’t make me sleep. Hoare talked about the division between the academic practices and the commercial world doing many comparisons and little jokes regarding the “I’m a scientist, I’m a engineer” world.

Keith Braithwaite started his talk “Adopting agile is harder than you’d like but easier than you’d think” by comparing costs of a developer and hardware costs. Keith showed some statistics of how people improve productivity by using bigger monitors and how these hardware costs are related to the developer costs. According to him, if your company don’t gives you a big monitor, they are loosing money due to loss in productivity. Other comments he did were about pair programming where he defends its use in an all the time basis, saying that “choosing to work alone, is to choose have less quality in your code”. In a rant about Rockstars developers, Keith said that them should not be part of a team but hired as consultants or contractors instead. Finishing his talk, Keith presented some points to consider in order to know if agile methodology is working in your team which are: estimates converge, quality remains high over long periods and the team by itself find new approaches to work better.

“Web-oriented architecture” and his other talk “Transforming software architecture with Web as platform” by Dion Hinchcliffe predicts the obvious where most the applications will be web-based and web-oriented and still following the “always beta” philosophy because “the best products are never finished”. According to Dion, the web oriented architecture is strongly based on REST plus the use of mashups, integration and widgets. Dion said we are missing portability in our applications, so he believes that by using OPML to exchange data, we’ll be in the right way to the web-oriented architecture.

Martin Fowler, who doesn’t need presentations, in “3 years of real word ruby” gave us an overall idea of how ruby was introduced in the projects inside ThoughtWorks. Martin talked about how people were dealing with ruby, how the productivity was affected and many other considerations of using ruby for real world projects. According to Martin, there are 41 projects made with ruby. One thing Martin said, was how people felt when they need to go back to work with languages other than ruby. Not surprisingly (for me) most of the people didn’t want to go back to work with other languages, mostly because the easy of use of ruby. About ruby performance in the projects, Martin said “Ruby is slow, but that’s not the bottleneck in most of applications. The biggest cause for slowness nowadays is accessing database” . Regarding the tools to develop with ruby, once again, wasn’t any surprise for me. Nobody in the team feel the need for a IDE like Eclipse. All in all, nothing new for me in his talk, but it’s always good to hear from guys like Martin.

“Agility: possibilities at a personal level” by Linda Rising was a really weird talk. During 95% of its time, she talked about Caffeine and the way it affects a person’s health. It was for sure a nice talk and Linda definitely knows how to keep people’s attention. The message that she tried to present was that being agile can be (bad) the same way “caffeine” is for our health because being agile makes you feel energized, stimulated, addicted to work and makes work be a fun thing but our body and mind are not ready for such “energy”.

Joseph Pelrine in “Coaching self organizing teams” was about how to make people do things without telling them directly. It’s all a matter of achieving the right behavior which for Joseph is a function of people vs environment. Self organizing teams have a emergent behavior and are in general conditioned to the “first fit pattern match”. It means, they make decisions based in what they experienced. This kind of team needs diversity in terms of behavior in order to stimulate a evolving behavior as a team. A team is not just a bunch of people working together, they need “heat” to move and work better. According to Joseph, it’s near “chaos” when people do they best. To defend his idea, he states there are team “temperatures” to keep track:

  • burning, when the team is in a organized chaos where everything is done fast, synchronized and without errors. According to Joseph, although this is what every team manager wants this “temperature” only can be maintained for short periods because it can drive the team crazy.
  • cooking, when the team have everything fitting nicely and properly. Projections are made with realistic dates and everything flows to achieve a goal without help of the team manager.
  • stagnating, when people in the team starts procrastinating the tasks because they don’t realize the real value of it.
  • congealing, the team is lazy. They know they could do something better, but they are too lazy to do it.
  • solidifying, the team starts adding bureaucracy for everything just to procrastinate even more the tasks.

One important lesson from Joseph was if you want to change a team, you’ll need to stimulate the team’s network by creating confidence among the members of the team. How can you do that ? It’s like flirting with somebody , first it requires a real context to apply, it means, something to talk about, then you’ll need a good environment, it means the place where it will evolve the stimulation.

There`s still hope

0 Comments | This entry was posted on Nov 05 2008

Ok, this blog isn`t about politics and I`m also not into politics, but for the first time in my life I believe a politician can really make a “real change”. Not only changes in USA, but in all the countries and the way people see the USA.

Congratulations Barack Obama !

Why I have been away

3 Comments | This entry was posted on Oct 22 2008

For those you don`t know, when I attended RailsConf Europe, I came to Europe to make a live test in a job I was applying. As you know by my blog post, RailsConf Europe was great. I just wrote one post about it, but that week was incredible busy for me. I still have my notes from the second day of RailsConf, but I don`t know if I`d post them.

The fact is: I got approved (yaaayyy ). So I back to Brazil to start arranging documentation to apply for a work permit in Spain (Madrid City). Now I`m in Madrid, working in the company. This changes a lot of things in my life, but it`ll be an amazing experience for me in any field.

Here i`ll learn a new language (spanish), work and learn with amazing people like Pratik Naik, Xavier Noria e Raul Benito, play guitar hero in the company when stressed, attend nice conferences in Europe like Goruco, RubyConf and others, meet new people in the effervescent nightlife of Madrid…

One last thing: My google summer of project went live yesterday (October, 21) and everything is working fine. In case you want to check it out the URL is http://www.christmasfuture.org/.

Thanks,

ps: In the picture is the amazing new terminal of Madrid`s airport

David Pache

3 Comments | This entry was posted on Oct 07 2008

I’m starting a new section in my blog where I’m going to present and recommend talent of many areas, but all related to web development. I believe it is very important this connection with what is being created around the web and us (developers), because besides being good to inspire ourselves, it help us to became more competitive and to ensure we are in a continuous learning, always focusing in our self improvement.

I’m going to present a designer, called David Pache, who brings a minimalist style that in my point of view is something the so called web 2.0 is all about: simplicity. The designer bests creations are his logos. You can see all the process of creating a logo, as well color studies in his “dacheboard” which is kind like a blog, where he wrotes about he develop his works.

Make sure to visit his portfolio. Bellow is just a sample of David’s work.

[David Pache website] http://www.dache.ch/

David Pache

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