Rodrigo Flores's Corner Code, Cats, Books, Coffee

octopress and capistrano

To deploy your octopress blog with Capistrano, you should do these steps:

First, add capistrano gem to your Gemfile. Then, after running a bundle install, run bundle exec capify . (or bin/capify . if you use binstubs) to generate the Capistrano files.

After that, you should add a content like this to your config/deploy.rb file.

# Set this forward agent option to not have to add your server's ssh public key to your repository's host authorized keys
ssh_options[:forward_agent] = true
require "bundler/capistrano"

set :keep_releases, 5
set :scm, :git
set :scm_verbose, false

# Set your repository URL
set :repository, 'YOUR REPO HERE'

# Set your application name
set :application, "YOUR APPLICATION NAME"
set :deploy_via, :remote_cache

# Set your machine user
set :user, 'YOUR SSH USER'

set :deploy_to, "/home/#{user}/apps/#{application}"
set :use_sudo, false

# Set your host, you can use the server IPs here if you don't have one yet
role :app, 'YOUR HOSTNAME', :primary => true

default_run_options[:pty] = true

namespace :octopress do
  task :generate, :roles => :app do
    run "cd #{release_path} && bundle exec rake generate"
  end
end

after 'deploy:update_code', 'deploy:cleanup'
after 'bundle:install', 'octopress:generate'

Now, you should add the group production to the development group on your Gemfile. Doing this, capistrano will be able to run octopress:generate on your server.

source "http://rubygems.org"

group :development, :production do
  gem 'rake', '~> 0.9'
  gem 'rack', '~> 1.4.1'
  gem 'jekyll', '~> 0.12'
  gem 'rdiscount', '~> 1.6.8'
  gem 'pygments.rb', '~> 0.3.4'
  gem 'RedCloth', '~> 4.2.9'
  gem 'haml', '~> 3.1.7'
  gem 'compass', '~> 0.12.2'
  gem 'sass-globbing', '~> 1.0.0'
  gem 'rubypants', '~> 0.2.0'
  gem 'rb-fsevent', '~> 0.9'
  gem 'stringex', '~> 1.4.0'
  gem 'liquid', '~> 2.3.0'
end

gem 'sinatra', '~> 1.3.5'
gem 'capistrano'

Finally, before doing the first cap deploy, do a git clone of your blog’s repository on the server (or try to connect through ssh to the repository server on your blog server), you will need to use the -A option on ssh command to forward your keys. This is needed because ssh asks for the fingerprint confirmation on the first ssh connection. As capistrano won’t do the ‘yes’ on the confirmation you should do it manually.

Doing this, you will be able to deploy your blog through capistrano. Do you have any tips on how to improve this capistrano recipe ? Please say them on the comments :).

Ruby Patterns: Method with options

This is a series about Ruby Patterns, which will explain some common uses of Ruby syntax. The first post is about methods with options.

Let’s start with an example where it can be useful. Suppose, you’re given an object and you should write a method that prints the object’s attributes in HTML. Also, you’ll also have to follow this other requirements:

  • You may specify the attributes that you want to show (by default you should show all of them);
  • You may specify the attributes that you don’t want to show (by default, you should show all of them, i.e. this list is empty);
  • You may specify the format: possible formats are :ordered_list, :unordered_list, :table (by default, present it as a :table);
  • You may specify the strftime format of the objects of Time type (default is :month/:day/:year :hour::minute :timezone in strftime format);
  • You may specify the strftime format of the objects of Date type (default is :month/:day/:year in strftime format);

So, given this requirements. Let’s write a function:

def object_to_html(object, only=nil, except=[], format=:table, time_format="%m/%d/%Y %H:%M %t", date_format="%m/%d/%Y")
  only ||= object.attributes - except

  if only - except != only
    fail "You can't put in except an attribute that you've put on only"
  end

  # Code that does what we proposed
end

Some examples of the usage of this function (and what someone will say after reading your code):

object_to_html(user) # Seems OK
object_to_html(user, nil, :encrypted_password) # What is this nil ?
object_to_html(user, [:email, :phone, :created_at], [], :ordered_list, "%d/%m/%Y %H:%M", "%d/%m/%Y") # WTF is this empty array ?
object_to_html(product, nil, [], :table, "%d/%m/%Y %H:%M", "%d/%m/%Y") # Gosh. My eyes are bleeding. Call an ambulance.

What a creepy code! If you want to change the last attribute, you will have to know all the default values of the other ones to be able to change it. You will also have to know (or constantly look at its implementation or documentation) the exactly order of the attributes. Also, if you decide to remove one attribute, you will have to find all the calls to this method and change it on all of them. Definitely, this is what I call ugly code: difficult to use and hard to maintain.

So, this pattern comes in handy: method with options!

def object_to_html(object, options={})
  default_options = {
    :format => :table,
    :only => nil,
    :except => [],
    :time_format => "%m/%d/%Y %H:%M %t",
    :date_format => "%m/%d/%Y"
  }

  options = options.reverse_merge(default_options)

  options[:only] ||= object.attributes - options[except]

  if options[:only] - options[:except] != options[:only]
    fail "You can't put in except an attribute that you've put on only"
  end

  # Code that does what we proposed (now it uses the options hash instead of local variables)
end

The same usage examples come along:

 object_to_html(user)
object_to_html(user, :except => [:encrypted_password])
object_to_html(user, :only => [:email, :phone, :created_at], :format => :ordered_list, :time_format => "%d/%m/%Y %H:%M")
object_to_html(product, :time_format => "%d/%m/%Y %H:%M", :date_format => "%d/%m/%Y")

Now to the explanation of how this works: the Hash#reverse_merge! method does the key role here. It merges the two hashs (the one containing the default values with the one that was given as a parameter) and in case of the same key in both, it keeps the one that belongs to the Hash that received the method call (in our case, the one given as a parameter to the method). The method is called reverse_merge because the Hash#merge method solves the conflict in the opposite way: in case of the same key in both, it keeps the one that belongs to the hash given as argument on merge. We can easily use merge instead of reverse_merge if we write the line 10 this way:

options = default_options.merge(options)

And then the code would work the almost the same way: the only difference is that instead of accessing local variables we may access the arguments in the options hash, but this can be easily converted. Also, note that we’re adding a bang (!) so, it will modify the hash and do the merge on itself instead of not modifying and returning other instance of hash.

Also, if you want to enforce that one option is always given, you can do this:

begin
  options.fetch(:format)
rescue KeyError # Hash#fetch raises KeyError when a key is not found
  raise ArgumentError, "The :format option should be passed"
end

Doing this, you will treat a missing argument the same way Ruby does with the function calling. However, I’m not a big fan of this approach: I think that if an argument is mandatory, it should be passed as a regular argument and not on as a function.

This pattern is heavily used on famous Ruby libraries like Rails, Bundler or Devise and plays a big part on pretty DSLs like Rails routes or Gemfiles. So, IMO, you should use it wherever you find a need to include more than 2 or 3 arguments on a function. Also, it is possible to use this on Javascript: if you take a look at jQuery’s ajax function it works the same way: you can pass the url as the first argument and the other parameters (like callbacks, fallbacks, urls, etc) as an object.

A big disadvantage in doing this is that it is very difficult to know what is the default options, and even looking at your code, you may only understand what is the default behaviour passing through all the code (which is far from good). So, I suggest that you document the default parameters and what does they mean like Rails do in this example with the has_many method.

UPDATE: As Rafael França suggested, I’m not overriding the argument anymore. As hashes are passed as a reference, when you execute merge! you actually change the parameter outside the function as an undesirable side effect.

UPDATE II: Adam Meehan reminded me on the comments that Hash#reverse_merge is part of ActiveSupport and not part of Ruby standard library. To be able to use it, you will have to require activesupport/core_ext/hash.

conference speaker 101

TLDR: Here I talk some of the things that helped me to present my first talk at a conference

Last year, I presented my first talk at RS on Rails, which is a Rails (and Ruby) conference which happens in Rio Grande do Sul at the south region of Brazil.

Before that, I never had given a 40 minute talk at a conference (I’ve only talked about 20 minutes at FISL 2008 on a short talk about Archlinux) and as a regular geek I’m shy and I don’t think I’m someone which masters the skills to delivery great talks like Steve Jobs.

This posts intends to tell you some tips that helped me to prepare my talk, how I rehearsed it and what I did on stage.

Content is king

If you’re not a well known speaker, people will not watch you unless you have something great to tell them, so spend some time thinking about nice things to talk and if a regular attendant will be able to watch it. I remember about going to an event where the speaker talked about Ruby’s meta programming and 90% of the attendants were doing their first steps on Ruby and Rails. The speaker was really a good speaker and taught really nice things, but clearly he missed the point talking about this on an event with that amount of newcomers. You should measure if the subject that you will talk is too basic or too advanced for the event.

Before writing any slides or sending any proposal, create a list of topics that you will talk about. Validate this with a colleague and see if he thinks that you had chosen well the topics. If you’re not secure about the topics and your colleague didn’t get the point of your talk, try to write a draft of the slides and present it to your colleagues in order to get some feedback. If you have friends that talked on events, you can get valuable feedback and discover what is worth talking and what isn’t.

Study about creating great slides

Every time I think about boring things, I remember a professor in college that used to give his lectures using power point slides. I remember that most of the students slept or played games on their mobile phones. You may say that students should pay attention on what professors say, but in our defense, I say that his lectures were really really boring. Obviously, even if he is a great researcher and knew a lot about the subject he was teaching, he lacks knowledge on presentation preparation to keep the audience focused.

Of course, lectures and talks are more than great slides. But in order to deliver a great talk, you should prepare beatiful slides.

But how do we prepare a good talk ? There is some resources that teaches you how to prepare great talks. Due to a friend recommendation, I’ve read Presentation Zen: Simple Ideas on Presentation Design and Delivery by Garr Reynolds before preparing the slides. This book tells you how to prepare and present a great talk and design great slides. I’ve also watched the talk Your Slides Suck by Shane Becker, that tells you how not write slides. Other resource that was published after my presentation is Zach Holman’s blog post about slide design which tells developers (that generally lack design skills) how to create beautiful and great slides.

Rehearse, rehearse, rehearse

When you’re writing slides, you probably know what to say on each slide. But, do you really know how to connect it to the previous and the next slide? Also, you know how to explain it clearly? As expected your answer is probably “no”. So, you should rehearse. Check if you’re saying what you need to say in your presentation time frame without having to hurry or skip any subject. Also, check if you can explain clearly every topic (if you’re afraid to forget something and your presentation software have this feature, write a note visible only to the speaker about what you’re supposed to talk). If you’re not secure, present it to your colleagues and get some feedback about your explanations or examples. When I wrote my talk, I present it at least 4 times to my colleagues at Plataformatec and every rehearsal I got valuable feedback about it. I also presented it to myself several times, and the last one was on the night before the event.

Also, ask a friend to play the devil’s advocate and find flaws on your talk.

Rehearsing is really important, but keep in mind that you’re rehearsing to practice what you will say, not exactly what you will say. Don’t try to memorize everything, because listening to someone reading (or saying something that has been memorized) is way boring of listening to someone telling a story (unless you’re an actor, which is probably not the case).

On the stage

When you’re on stage, you will probably get nervous with all that people watching you. I remember, while presenting a lightning talk on Ruby Conf Brazil, a moment when I forgot what to talk and, on stage, I saw the crowd looking at me, and I thought I would not be able to continue presenting. Fortunately, I quickly remembered what to say and continued my talk. Asking my friends later, they said that this moment took around a few seconds, but appeared to me that it took at least fifteen seconds.

You will probably get nervous, but if you have rehearsed it enough you will calm down and keep it going.