Posts by Rodrigo Flores

Nos próximos dias 30 e 31 de agosto, estaremos presentes na Ruby Conf Brasil com três palestrantes!

No dia 31, às 9h40, José Valim falará na Sala 1 sobre concorrência e sobre o papel e a importância disso no desenvolvimento de aplicações.

Às 11h, na sala 2, Carlos Antonio falará sobre como usar Active Model para escrevermos aplicações melhores.

Por fim, às 11h50, na sala 1, Rafael França falará sobre as entranhas do Rails e as grandes novidades do Rails 4.

Não deixe também de votar em nossos Lightning Talks, que serão realizados no primeiro dia, a partir das 18h20:

Nos vemos lá!

Last week, while developing a feature I had some code like this in a view:

link_to_unless @post.url.blank?, "Link to post", @post.url

Where url is an attribute of type String. As people usually don’t like negative conditionals, we can easily rewrite this code as:

link_to_if @post.url.present?, "Link to post", @post.url

However, we can clean our code a little bit using the #{attribute}? method.

link_to_if @post.url?, "Link to post", @post.url

The #{attribute}? method is a method defined automatically by Active Record. Intuitively, you may think that it is equivalent to !!url and then would evaluate to true when an empty string, but Rails is smart enough to detect that the attribute is a string and returns the equivalent of !url.blank?, as you may see in these lines in Rails source code, which proved itself very useful.

Active Record defines many other attribute methods like that, for example url_changed?. What about you? What is your favorite Rails attribute method?

After 4 months of our last major version release, we’re releasing Devise 2.1.0, which includes several bug fixes, some new features and the removal of features deprecated on Devise 2.0. If you’re eager to do the update, please check Devise’s wiki page about Upgrading from 2.0 to 2.1. You can also check the changelog or the commits between 2.0.4 and 2.1.0.

Encrytable is now a gem

As it was only used for old encryption algorithms like sha1 or md5, we have extracted encryptable module to a separated ruby gem. So, if you’re using the encryptable module, you should only require it on your Gemfile and you’re good to go!

Check fields

To allow a developer to cherry-pick which features they want to add to their models, Devise splits its behaviors into modules. One of the consequences of such splitting is that you don’t know if the persistence layer provides all fields required by the behavior. For example, the database authenticatable module requires a encrypted_password field. If the field does not exist, you will end up getting an error during a request. Usually those fields are automatically added to the migration when you call the devise generator, but if you decide to include a module after, you can easily forget to add the new fields.

That said, in order to provide faster feedback, Devise now has a method that checks if a given class is missing any of the required fields and raises an error if so. You can call this method as follow (in case your Devise class is User):


We’ve implemented this feature in an agnostic way, to not depend on a specific ORM, but only to verify if the instance responds to the required fields. So even if your ORM does everything through method_missing, you should be able to use this method (we’re relying that you also have implemented a working respond_to?, which is strongly recommendeded when using method_missing).

When check_fields! is called, Devise will detect the included modules in the given class and, if there is a missing attribute, it will raise a Devise::Models::MissingAttribute exception with a message telling you all required fields that doesn’t exist. You can easily use that method with your favorite test framework:


And then you will be able to check if your migrations have added the correct fields to your database.

A message to module maintainers

If you’re a maintainer of a Devise module, you should add a method to each of your modules called self.required_fields(klass) that returns an array of required fields. If the method is absent, you will get a deprecation warning.

UPDATE: Fixed a class name and corrected a grammar error.

This article is about our Hacking Evenings, a weekly session in which we gather our team and do something to improve our knowledge. We talked about it on Ruby Conf Brazil and Ruby Conf Uruguay. You can see the slides here:

We’ve always worried about how to disseminate knowledge inside PlataformaTec. As a company with 13 employees (8 developers, 1 designer, 2 business analysts and 1 project manager), we all know that someone always has something new to share and that everyone else can learn from it.

As regular speakers in Agile and Ruby events, we usually rehearse our talks with our colleagues in order to get some feedback and improve them. But those rehearsals happened at best once a month.

Some months ago I read Chad Fowler’s Passionate Programmer book. In this book, Chad said about Brown Bag sessions, which is a lecture or talk given at lunch time (the name “Brown Bag” comes from the food packet that people usually brought, usually brown bags). Reading this chapter was the motivation I needed to gather our team and discuss the requirements to make our own meetings happen.

The first requirement is inherent to a consultancy company which sometimes has people working from its clients’ offices, making it harder to find a day and hour when everyone can participate. After some discussion, we decided to do that on tuesday evenings. When we decided to do that most of our team could participate but, as time goes by, the ones that couldn’t changed their schedules to fit our hacking evening there.

The second requirement was (IMHO) easier to solve: the resources. We have a big flat TV in our office since september, but before that we had only 24 inches monitors which were also fine and that you probably already have in your office. We also needed motivated people to spend some time preparing something to share. As a company that always looks for mastery, this was not hard and since we started someone always had something to share (but in case nobody has, we can watch a screencast or a talk at confreaks, which requires almost zero preparation).

The third requirement is to have something to eat. Because it is after the working hours, people are usually starving, and we can’t have fun in our hacking evenings without grabbing something to eat. In first sessions, we ordered some Pizza, which was great but expensive. So, we decided to prepare something on our own. Before starting we usually go to a near supermarket and buy the ingredients. We already prepared ham and cheese sandwiches, hot-dogs, cheeseburgers and tapioca (a brazilian wrap made of manioc).

OK, we’ve satisfied our requirements. But how to keep people motivated and participating on every session? Here are some tips:

  • Make it a habit: if we do it every week at the same day and time, it is easier for everyone to commit themselves to participating. Ok, not everybody will go every week, but once we introduced this habit into our colleagues minds, they will avoid scheduling other activities in the same time and participate
  • Accept any idea: the main idea is to spread knowledge. Can it be a typical talk? yes. Can it be a design or agile workshop? Yes. Can it be an open-source hacking session with someone helping the others to do bug-fixes and developing new features? Yes.
  • Invite friends to talk and watch: If you have a friend that knows a lot about some subject and can improve the knowledge of your company, why not call him to participate ?
  • Have fun: this is, by far, the most important tip: without having fun, people will not participate. Try to make it fun to make people spend a nice time. We’re talking about after-hours so, if it is not fun, people will not participate.

How do you disseminate your knowledge internally? Do you usually do Brown Bag Sessions? What activities do you usually do ? Would you recommend an activity for us?

No último dia 13, participamos do RS on Rails com a palestra: “Código Saudável => Programador Feliz”. O evento foi sensacional e muito bem organizado pelo pessoal do Guru RS. Assistimos palestras de excelente qualidade e tivemos a oportunidade de compartilhar um pouco da nossa experiência. Os slides estão a seguir:

A palestra abordou três tópicos que consideramos importantes em aplicações: Arquitetura, Modelos e Produção. No primeiro tópico falamos como você pode estruturar melhor seus controllers, para eles fazerem apenas o que devem realmente fazer e deixar o trabalho de roteamento com as rotas, e também sobre um costumeiro mal uso do princípio DRY. Como uma boa referência para esses assuntos, recomendamos a leitura desse artigo, publicado no blog da Thoughbot e assistir a palestra do David Chelimsky.

Também falamos sobre modelos e como eles podem ficar bem desorganizados. Sugerimos três possíveis melhorias: extrair responsabilidades de um modelo para uma classe usando o composed_of; extrair lógicas em comum entre modelos usando Concerns; e ficar de olho em como o ActiveRecord usa o banco usando a gem query_reviewer e entender como seu banco funciona lendo a documentação ou alguma literatura de referência nesse assunto (High performance MySQL ou Postgre 9.0 High Performance caso você use um destes dois bancos).

Sobre aplicações em produção, falamos sobre algumas dicas sobre como manter sua aplicação sempre bem monitorada em um ambiente em produção. Para monitorar visitas, falamos sobre o Google Analytics e o Piwik. Para ter controle dos erros da sua aplicação em produção, falamos sobre o Airbrake e o Exception Notification. Para ficar de olho na performance de sua aplicação, falamos sobre o Request Log Analyzer e o New Relic. Para monitorar o estado do servidor de sua aplicação, as ferramentas mencionadas foram o God, Monit, Server Density e o Pingdom (sendo este último apenas para monitorar se sua aplicação caiu). Também sugerimos manter uma nota alta no YSlow; usar deploys automatizados com o Capistrano e usar uma solução de backup (nós normalmente fazemos isso usando uma tarefa de backup agendada via Cron e sempre sincronizando com outras máquinas).

Agradecemos o pessoal da Softa pela hospitalidade, pelos happy hours em seu escritório e ao Guru RS pelo excelente evento! Nos vemos em novembro no Ruby Conf!