Fork me on GitHub

Deployment Recipes – Deploying, monitoring and securing your Rails application to a clean Ubuntu 10.04 install using Nginx and Unicorn

Agile Web Development With Rails

Agile Web Development With Rails

You can get a PDF version of this tutorial here.

If you’re a developer, setting up a server might not look like something you’d do yourself. Most of the time you have a sysadmin in your team/company/business that can do the job for you. But knowing how to configure a server might make your life easier if you’re rolling on your own so let’s take a look at how we can configure a clean slate Ubuntu 10.04 server machine to run a Ruby on Rails application.

This example used a just created Ubuntu 10.04 image from Rackspace, but you should be able to follow it on any Ubuntu 10.04 install, even a local one.

With this tutorial you’ll learn how to:

  • Install the libraries usually necessary to run Ruby on Rails application;
  • Setup Nginx as the HTTP server proxy and statics assets server;
  • Setup Unicorn as the application server that’s going to run your application;
  • Setup Monit to watch over the processes
  • Setup some basic firewall rules
  • And finally deploy your Ruby on Rails application to it;

Remember that this tutorial is given in an “as is” basis and you should backup all system files we’re changing here.

Continue reading “Deployment Recipes – Deploying, monitoring and securing your Rails application to a clean Ubuntu 10.04 install using Nginx and Unicorn” »

Tags: , , , , ,

Asynchronous email deliveries using Resque and resque_action_mailer_backend

The Rails 3 Way

The Rails 3 Way

Check the GitHub repo here and a sample application using it here.

If you have ever sent emails using ActionMailer during a user request you probably noticed that if the email sending fails or takes too long your user might not be really happy with the speed of your application. Making the email sending process an asynchronous one is usually the simplest solution for this problem and there are plenty of tools to do that like ar_mailer, that stores emails in your database and then uses a specific daemon to send them.

Continue reading “Asynchronous email deliveries using Resque and resque_action_mailer_backend” »

Tags: , , ,

Produzindo um avião com métodos ágeis

Produto final produzido no curso de CSM

Produto final produzido no curso de CSM

Este último sábado foi também o último dia da minha disciplina de Introdução aos Métodos Ágeis e Scrum da especialização em Metodologia para Engenharia de Software na Faculdade iDez. Como projetinho de última aula resolvi roubar a idéia que eu havia visto no curso de Certified Scrum Master que o Michel Goldenberg ministrou em Recife no início do ano.

A idéia básica é que os alunos fariam um produto (que no caso do curso foi um folder com de propaganda) e se utilizariam do Scrum pra produção do mesmo. O trabalho foi simples e exigiu muito mais organização e foco por parte da equipe pra entregar o folder pronto do que trabalho duro propriamente dito.

Muitas idéias diferentes surgiam enquanto estávamos planejando e começando o trabalho, se tivéssemos seguido todas, o produto não teria sido entregue, mas o tempo finito e a comunicação constante da equipe nos mantiveram na linha pra finalizar a tarefa. No fim foi uma ótima forma de cristalizar o conhecimento básico de Scrum que foi passado durante os dois dias de curso e eu sabia que eu não podia terminar essa disciplina de Scrum sem fazer o mesmo com o pessoal.

Será a Embraer?

Coloquei na cabeça que faria a dinâmica, mas faltava a idéia de “o que” produzir. Não queria repetir a idéia dos folders de propaganda, então o que seria um trabalho manual interessante pra colocar o pessoal pra produzir? Aviões, claro!

Na brincadeira, cada equipe ficaria responsável por produzir um avião com o material disponível dentro do tempo estimado de uma hora e meia. Essa hora e meia consistiria tanto no tempo pra planejar a construção do avião (Release e Sprint Planning Meetings) como efetuar a construção em si. Dividi então o tempo nos timeboxes:

  • 20 minutos iniciais – Release Planning – cada equipe tem que fazer o planejamento do release, que vai conter dois sprints e também fazer o planejamento dos dois sprints;
  • Dois sprints de 30 minutos – aqui é onde eles finalmente executam o trabalho, esses 30 minutos são divididos então em 3 blocos de 10 minutos, com um Daily Scrum entre cada um deles.
  • Ao fim de cada sprint a equipe deve fazer uma breve apresentação sobre o que eles conseguiram produzir e depois avaliar o que deu certo ou não durante o trabalho (a retrospectiva do sprint);
  • Terminados os sprints as equipes demonstram o seu produto final pra todos na sala;

A idéia é que o evento todo seja simples, nós fazemos priorização e planning poker durante os 20 minutos iniciais, mas não consideramos velocidade ou fazemos o burndown do projeto. O foco maior é nos timeboxes e no objetivo final que é entregar o avião pronto. Se a equipe percebe que tudo o que eles planejaram não vai ser entregue até o fim do tempo, eles precisam se reorganizar e diminuir o escopo pra poder ter um produto completo ao fim das duas sprints.

Equipe Boeing planejando o trabalho

Equipe Boeing planejando o trabalho

Montando as equipes, ambiente e materiais

O meu caso eram duas equipes com 8 pessoas cada, das 8 pessoas, 1 era o Scrum Master, 1 o Product Owner e os outros eram a equipe de desenvolvimento em si. O Product Owner não trabalha efetivamente, mas ele pode direcionar a equipe e aceitar ou não o trabalho sendo feito.

O Scrum Master também não deve fazer trabalho diretamente, seu serviço é apenas resolver impedimentos na equipe, como falta de material. Eu também andei atrapalhando as equipes conversando besteira, removendo material, ocupando os desenvolvedores com outros trabalhos, pra manter os Scrum Masters ocupados.

O material necessário pra cada equipe é:

  • 2 garrafas de refrigerante de 2 litros (preferenciamente garrafas que não tenham detalhes no formato, como as de Guaraná Antartica);
  • 2 tesouras;
  • 1 estilete;
  • 2 folhas de cartolina guache/grossa;
  • 2 folhas de cartolina fina;
  • 1 conjunto de canetas hidrocor;
  • Baralhos pra planning poker;
  • Post-its e index cards/folhas de resumo;
  • 1 pacote de palitos de churrasco, preferencialmente de bambu;
  • 1 rolo de fita adesiva transparente;
  • 1 régua grande (ao menos 50cm);
  • Os dois produtos finalizados após os 2 sprints

    Os dois produtos finalizados após os 2 sprints

    Lições da primeira vez

    Não levei estiletes, foi bem difícil pro pessoal cortar as garrafas, também levei apenas uma tesoura pra cada grupo e isso foi um problema, já que muita coisa precisava ser cortada, ter duas tesouras teria agilizado muita coisa. Levei apenas um rolo de fita adesiva e ela rodou demais entre as duas equipes, ter um rolo pra cada equipe também teria complicado menos as coisas.

    No fim, acho que o saldo final da brincadeira foi bem positivo, os dois grupos produziram os seus aviões e cada um completamente diferente do outro (e eles estavam lado a lado dentro de sala). As equipes mudaram o escopo e a idéia do que iam produzir baseados no caminho que a “construção” estava tomando (a equipe Boeing só resolveu realmente construir um avião com as duas garrafas no segundo sprint, quando a equipe Teco-Teco já estava com o esqueleto do avião quase todo pronto).

    Dinâmicas, jogos e atividades interativas no geral deveriam ser mais comuns no ensino em tecnologia, ainda está pra surgir uma forma de ensinar que seja mais completa do que envolver os alunos na atividade de verdade. Clique aqui pra ver a galeria de fotos completa com todas as imagens da aula.

    Tags: , ,

    If you’re cleaning up your user’s input in your views you’re doing it wrong

    Have you ever found yourself using the “h” view helper all around your views in your applications? Have you ever thought that cleaning up user input in views is a tedious, error prone and cumbersome job?

    You’re not alone.

    Continue reading “If you’re cleaning up your user’s input in your views you’re doing it wrong” »

    Tags: , , , ,

    Building your own ActiveRecord validation macros with validates_each

    A common task when writing your own Rails applications using ActiveRecord is creating your own validations for your models. While it’s perfectly correct to add the validation directly into the model you’re going to need it, sometimes you’d like to reuse the same validation logic in other models and we’re not really going to do a cut-and-paste here are we?

    Continue reading “Building your own ActiveRecord validation macros with validates_each” »

    Tags: , , ,

    Setting a far future expires header for your Rails app static assets in your Nginx server

    Even Faster Websites - Everything you need to now to improve you website's front end performance

    Even Faster Websites

    Setting a far future expires header for your static assets is one of the first front end performance improvements you must do in your web applications. This will tell your user’s browser to keep the static assets cached and they won’t make unnecessary HTTP requests just to see that the version they currently have is already the latest and this will surely improve your website’s perceived performance (yes, there’s a REAL and a user perceived performance for every application).

    Continue reading “Setting a far future expires header for your Rails app static assets in your Nginx server” »

    Tags: , ,

    Accessing the current request object on your mailer templates to generate links

    A common issue with mailer templates is that as they’re not being called from a controller you can’t get your hands on the request object and access properties like host_with_port. While you’re usually calling the mailers inside controllers and you could possibly hand the request as a parameter to it, it isn’t really nice to do this every time you need to send an email.

    <%= link_to 'Home', "#{current_request.protocol}#{current_request.host_with_port}/home" %>

    So, if you’re looking for a quick and easy solution to this issue, the current_request plugin is your friend, you can install it by calling:

    ruby script/plugin install git://github.com/mauricio/current_request.git

    The plugin works by setting the current request in a thread local variable that will be available until the end of the request, which means that you can use it safely in your templates, two new methods are added to all views, current_request, that returns, obviously, the current request being answered and current_host that will build the current host with port and protocol for you. Examples:

    Or you can just use a shorthand to the current host:

    < %= link_to 'Home', "#{current_host}/home" %>

    You can also use it wherever you want to access the current request (and not only on templates) by calling:

    CurrentRequest::Holder.current_request

    Why I am not using Masochism for my master-slave setups and why monkey-patching isn’t the only solution

    I got a message this morning from Gregg at Ruby5 asking why I wrote the master_slave_adapter plugin instead of using Technoweenie’s Masochism and I think the answer to this question deserves a little blog post (and the blog really needs some new content :P).

    Continue reading “Why I am not using Masochism for my master-slave setups and why monkey-patching isn’t the only solution” »

    Setting up your Ruby on Rails application in an Ubuntu Jaunty Jackalope (9.04) server with Nginx, MySQL, Ruby Enterprise Edition and Phusion Passenger

    There are many ways to deploy and run Ruby applications with the Ruby on Rails framework but it’s unlikely that you’re going to find a simpler and faster solution than using Ruby Enterprise Edition (REE from now on) with Nginx and Phusion Passenger. Nginx is a fast, scalable and lightweight HTTP server, that is able to serve a lot of content without using up all your memory and Passenger is a module that can be tied into Apache or Nginx to handle your Ruby (and RoR) applications automatically.

    When using Passenger you don’t need to worry about managing a pack of Mongrels or use a proxy HTTP server, Passenger lives inside your web server and just takes care of everything for you. Here you’ll learn how to use Passenger in conjunction with Nginx to deploy your applications in the wild.

    This tutorial assumes that you’re building a brand new Ubuntu server with none or little custom packages installed. Does this mean you can’t use this with an already customized server? No, but it’s easier if you can follow it step by step to avoid problems, as this has already been tried and tested to be sure that it works. We’re using MySQL here because it’s what I’m using right now but can easily change the apt-get calls to use whatever database you’re using yourself.

    Continue reading “Setting up your Ruby on Rails application in an Ubuntu Jaunty Jackalope (9.04) server with Nginx, MySQL, Ruby Enterprise Edition and Phusion Passenger” »

    Tags: , , , , , ,

    Quick Tip – Using to_s as a label and simplified link_to calls to your ActiveRecord models

    One of the things you’ll find in every rails application is links like this one:

    < %= link_to user.login, user %>

    Or maybe like this one:

    < %= link_to user.login, user_path( user ) %>

    Or maybe something ugly like this one:

    < %= link_to user.to_label, user_path( user ) %>

    How about throwing all of them and just doing it like this:

    < %= link_to user %>

    Cool, isn’t it?

    Now “how can I do that” you ask, it’s dead simple. First, remember that every object responds to a method called “to_s” and this “to_s” method is defined as “a method that returns a string representation of your object” in most programming languages, including Ruby.

    A string representation of your object is something human readable that would tell someone else what this object represents. “to_s” isn’t meant to be a debug like method, we already have “inspect” to do that, so why not put it to work and simplify our links?

    At every ActiveRecord model in your application you’ll define a to_s method that returns one (or maybe more, if needed) attributes of your object as a string (if they’re not strings, turn them into strings and return). Let’s see how your user would look like:

    class User < ActiveRecord::Base
      validates_presence_of :login
      validates_uniqueness_of :login
      def to_s
        self.login
      end
    end

    I decided that the “login” method is the one that best represents the User object and it’s also the one I want to use then someone else seers users on the website. They won’t see their real names by default, but their logins.

    Why is it better to do this with the “to_s” method instead of adding a “to_label” method to all objects? ‘Cos many helpers will already call the to_s method by default on your object (as we’ll see with the link_to helper), so you just get full compatibility for free. Check out our new link_to implementation:

    module ApplicationHelper
      #sample link_to override that will generate urls for active_record objects by default
      #if the first parameter is an active_record object and you just want a link to it,
      # you can call it just like this:
      # <%= link_to user %>
      # the helper will take care of generating the correct url
      def link_to( *args )
        options = args.extract_options!
        if args.size == 1 && args.first.is_a?( ActiveRecord::Base )
          super( *([ args.first, args.first ] + [ options ]) )
        else
          super( *( args + [ options ] ) )
        end
      end
    end

    If there’s only one object (besides the options hash) and it is an ActiveRecord::Base instance, just use the object itself as the url parameter (the real link_to helper will call polymorphic_url on it automatically) and also use the object as the link_to label (the first parameter), this will call the to_s method on our user and the link will use it as the label.

    What do you get with this?

    A seamless and clear way of defining labels for your models (the “to_s” method is part of the core of the language anyway) and also a simpler way of generating links for your objects. Common methods for object labels are very important because you can never be sure if the property you’re using today as a label will be used forever. Using the “to_s” method as the default “label method” will allow you to change the label property at any time with almost no change to other parts of the code.

    Tags: , ,