Using Capistrano with Passenger (mod_rails)

May 10th, 2008

I love Phusion Passenger. It takes away most of the pain from deploying. Instead of having to mess around with lengthy apache config files, you can just upload. POW!

Phusion Passenger — a.k.a. mod_rails — makes deployment of applications built on the revolutionary Ruby on Rails web framework a breeze. It follows the usual Ruby on Rails conventions, such as “Don’t-Repeat-Yourself”.

Installing Passenger

Another great thing about Passenger is that it’s stupidly easy to install.

gem install passenger
passenger-install-apache2-module

Then just follow the instructions that are displayed inside the terminal. It shouldn’t take more than 5-10 minutes max to get this shit on the road.

Passenger Meet Capistrano

You are using capistrano, aren’t you? Capistrano is a great tool, by Jamis Buck, for deploying your applications. It takes all the monotonous stuff and does it for you, which is nice.

If you’re not using capistrano, you can install it with the following:

gem install capistrano

Next, go to the root directory of your application and type:

capify .

This will set up your application for use with capistrano by creating a deploy.rb file and a Capfile. The deploy file is a recipe that will be used every time you deploy your application. Now lets look at making capistrano play with passenger.

The Deploy Recipe

I must confess something at this point: I’ve not actually tested this recipe yet as I’ve not had time. As far as I’m concerned it should work. If you find any problems let me know and I’ll fix them.

#############################################################
#	Application
#############################################################

set :application, "example"
set :deploy_to, "/var/www/#{application}"

#############################################################
#	Settings
#############################################################

default_run_options[:pty] = true
set :use_sudo, true

#############################################################
#	Servers
#############################################################

set :user, "jim"
set :domain, "example.com"
server domain, :app, :web
role :db, domain, :primary => true

#############################################################
#	Subversion
#############################################################

set :repository,  "http://www.example.com/svn/example"
set :svn_username, "jim"
set :svn_password, "password"
set :checkout, "export"

#############################################################
#	Passenger
#############################################################

namespace :passenger do
  desc "Restart Application"
  task :restart do
    run "touch #{current_path}/tmp/restart.txt"
  end
end

after :deploy, "passenger:restart"

From what I’ve read, the last few lines are all you should need to restart your application. This will be called after all deploy calls so you shouldn’t have to worry about anything.

Long live passenger

Some Stuff to Read

Here’s a list of a few things that are worth reading regarding capistrano and/or passenger.

Capistrano
Passenger (mod_rails)

Building a Social Network Site in Rails

April 25th, 2008

I’m not going to cover how to actually code an entire social network site in rails as all social network sites vary in their functionality (and it’ll take too long). I will cover plugins and other things you might find useful though.

Quick Start

If you don’t really want to do the coding but want to get a site up and running and soon as possible, you may want to have a look at Lovd by Less by the guys over at Less Everything. Lovd by Less contains user signups, galleries, blogs, comments and various other things that you might want, so it’s a great starting block for your site.

Social Network Plugins

Here’s a list of plugins that I’ve found to be useful while coding my own social networking site:

Restful Authentication

RESTful Authentication is pretty much the defacto standard for user authentication in rails. It allows easily set up user signups, login functionality and email notifications. The plugin doesn’t set up thing’s like forgotten password functionality but there is a great tutorial over Rails Forum.

# To Install
ruby script/plugin source http://svn.techno-weenie.net/projects/plugins
ruby script/plugin install restful_authentication
Paperclip

Paperclip is a brilliant plugin by Jon Yurek over at ThoughtBot. Paperclip is used for managing file uploads and attaching the files to models. You can read more over at my article: Paperclip: Attaching Files in Rails.

# To Install
svn export https://svn.thoughtbot.com/plugins/paperclip/tags/rel_2-0-2
piston import https://svn.thoughtbot.com/plugins/paperclip/trunk
Will_paginate

Will paginate is a great plugin for allowing paging of your records. Paging is a pain in the ass, but will_paginate makes it easy as pie.

# To Install
ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate
Acts_as_slugable

Acts_as_slugable takes the pain out of generating URL slugs. Everyone prefers meaningful URLs, so instead of showing a users page with ‘/users/231′, you can use ‘/users/jim-neath’. Nice.

# To Install
ruby script/plugin install http://code.dunae.ca/acts_as_slugable
White_list

White_list is yet another brilliant from Techno Weenie. The white_list helper will html encode all tags and strip all attributes that aren’t specifically allowed. It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters.

# To Install
ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/white_list/
Acts_as_commentable

Acts_as_commentable allows you to add comments to your models. It takes care of all the polymorphic associations for you, which is nice.

# To Install
ruby script/plugin install http://juixe.com/svn/acts_as_commentable
ReCAPTCHA

Fucking captchas. Unfortunately a necessary evil. If you’re going to use captchas then you might as well help to digitalise books. The reCAPTCHA plugin utilises the reCAPTCHA service which digitalises books by making users input the text.

# To Install
ruby script/plugin install svn.ambethia.com/pub/rails/plugins/recaptcha/
Acts_as_taggable_on_steroids

Everybody loves tagging, surely? Tag pictures, videos, blog posts, whatever you want. Acts_as_taggable_on_steroids is a great plugin for allowing your users to tag their stuff. It allows tag clouds and all that web 2.0 jazz everyone seems to love.

# To Install
ruby script/plugin install http://svn.viney.net.nz/things/rails/plugins/acts_as_taggable_on_steroids
Exception Notifier

Exception Notifier is a must have. It emails you when your live application fails. No matter how much testing you do, no doubt there’s going to be a scenario where it fails and when that happens you want to know.

# To Install
ruby script/plugin install exception_notification
Throttler

This is one of my favourite plugins. Say your site get’s slashdotted of dugg and you end up with immense traffic, the main thing is to keep your site up and running. This is where throttler comes in. You can throttle certain actions on your site when your server load is above a certain level. So you could disable video uploads while your server load is above x to prevent your server from crumbling.

# To Install
ruby script/plugin install http://svn.kabisa.nl/rails/plugins/throttler
Backup_fu

You’ve been working on your social network site for months and finally the traffic is coming in and you have a decent user base. Then one day your server dies and you lose all your data. Woe is you. You should have backed up. Using Backup_fu you can automatically backup your database and files to Amazon S3.

# To Install
sudo gem install aws-s3
ruby script/plugin install http://backup-fu.googlecode.com/svn/backup_fu/
Fischy Friends

Fischy_friends is a plugin by Daniel Fischer. It’s a great starting point for a friends system. I’ve used it on a couple of my own projects and it’s worked great for me.

# Github
http://github.com/dfischer/fischyfriends/tree/master

Other Useful Tools

SWFUpload

I love SWFUpload. It uses a small flash file to allow users to upload multiple files at once. The front end is completely open and coded in javascript so you can customise it how you like. You can see the demos here.

Download: http://swfupload.googlecode.com/files/SWFUpload%20v2.0.2.Release.zip

TinyMCE Text Editor

TinyMCE is WYSIWYG editor coded entirely in javascript. It’s useful for the less techno savvy of your users (which will no doubt be most). There’s a whole load of plugins available for the editor so it’s highly extensible.

Download: http://prdownloads.sourceforge.net/tinymce/tinymce_3_0_7.zip?download

FFMPEG/Mencoder

FFMPEG is a command line utility to convert various formats of video into other formats. The main use you’ll want to use this for is to convert videos into flv files for use with a flash video player.

JW FLV Media Player

The JW FLV Media Player (built with Adobe’s Flash) is an easy and flexible way to add video and audio to your website. It supports playback of any format the Adobe Flash Player can handle (FLV, but also MP3, H264, SWF, JPG, PNG and GIF). It also supports RTMP and HTTP (Lighttpd) streaming, RSS, XSPF and ASX playlists, a wide range of flashvars (variables), an extensive javascript API and accessibility features.

More Useful Resources

Adobe AIR Free PDF Download

April 18th, 2008

I honestly don’t know the first thing about AIR. I’m an AIR-dunce. Adobe to the rescue! POW!

Adobe are offering the updated PDF version of Adobe AIR for JavaScript Developers (Pocketguide) under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 license (someones made that up).

You can download the free PDF here. Kudos to Adobe and the AIR team for being awesome bastards.

Credit: This was originally posted over at Ajaxian so credit goes to them for a great find.

Paperclip: Attaching Files in Rails

April 17th, 2008

Paperclip is an awesome rails plugin by Jon Yurek at Thoughtbot. It is one of many plugins currently available that cater for file uploading and thumbnailing (see: Attachment_fu, file_column, etc). Now a quick quote from Jon:

For some reason, file attachment is annoying. I don’t know why, and I know a lot of people have attempted to solve the problem in the past, myself included. Yet it still is. Having gotten fed up with gotchas and design decisions that we didn’t agree with, I went and wrote Paperclip on the plane to RailsConf last year. We’ve been using it here in various forms since and IMHO it’s the way to handle uploads, and finally decided that it should be released.

Installing Paperclip

You can install Paperclip using a variety of different methods:

svn export https://svn.thoughtbot.com/plugins/paperclip/tags/rel_2-0-2
piston import https://svn.thoughtbot.com/plugins/paperclip/trunk

You can also grab Paperclip from the git repository.

Quick Note: If you’re a windows user, you’re going to need to go for the trunk version as this contains a fix to a problem that basically meant that Paperclip borked.

Basic Usage

class User < ActiveRecord::Base
  # Paperclip
  has_attached_file :photo,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>" }
end

Attached files don’t need to have a seperare model (thank god). Your attachments are treated just like any other atribute. Images aren’t saved until your model is saved. There are a lot of bonus options but I’ll cover them towards the end of the article.

class AddPhotoToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :photo_file_name, :string # Original filename
    add_column :users, :photo_content_type, :string # Mime type
    add_column :users, :photo_file_size, :integer # File size in bytes
  end

  def self.down
    remove_column :users, :photo_file_name
    remove_column :users, :photo_content_type
    remove_column :users, :photo_file_size
  end
end

Don’t forget to add these columns! Otherwise you’ll end up scratching your head and wondering where the hell you went wrong. The first part of the column names is the same as whatever you’re called your attached file. In our case that’s photo. Now update your database:

rake db:migrate

Now that your database is sorted, we can start working on adding some content. In your view you can add a file field like you would normally:

<% form_for :user, :html => { :multipart => true } do |f| %>
  <%= f.file_field :photo%>
<% end %>

Don’t forget the :multipart => true part or everything will fail. Then you will cry.

Now in your controller, you don’t need to do a thing (hooray).

def create
  @user = User.create(params[:user])
end

You should now be able to upload user photos to your hearts content.

To display your user’s photos all you need to do is call:

<%= image_tag @user.photo.url %>
<%= image_tag @user.photo.url(:thumb) %>

The first call will display the original image. The second one will display the thumbnail image. Easy, yes?

Paperclip Options

Now that you’ve seen how easy to use and awesome Paperclip is, let’s have a look at some of the additional settings you can use:

has_attached_file :photo, :url => "/:class/:attachment/:id/:style_:basename.:extension"

Using :url you set when your images can be accessed from. The above setting would mean that your files are located at URLs similiar to /user/photo/1/thumb_originalfilename.jpg”

has_attached_file :photo, :default_url => "/:class/:attachment/missing_:style.png"

The :default_url option is used if there is no attached file for a model. If a user doesn’t have any uploaded avatar you could use this option to set a default avatar to show.

has_attached_file :photo, :styles => { :normal => "100x100#", :small => ["70x70>", :jpg] }

:styles is a hash of thumbnail styles. The styles use the standard ImageMagick geometry rules. Paperclip also adds the ‘#’ option which will create square thumbnails that are nicely cropped.

has_attached_file :photo, :default_style => :thumb

:default_style is pretty straight forward. You can select a default style from your style list that will be called, instead of the original file, when you use @user.photo.url

has_attached_file :photo, :path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension"

Using :path you can select where the files are saved to on your box. If you change this, make sure to change the :url setting to relate to the new path.

has_attached_file :photo, :whiny_thumbnails => true

:whiny_thumbnails will raise an error if there is a problem creating thumbnails. Set to true by default.

Some Waffle

Paperclip is a great plugin. It has a smaller memory footprint than Attachment_fu, it doesn’t require the use of Rmagick (eugh) and it has all the options that I’ve wished that Attachment_fu had. Give it a try and let me know what you think

Again, maximum kudos to Jon Yurek and all the guys over at ThoughtBot.

Jim Neath is a 23 year old Ruby on Rails developer from Manchester, UK. Contact Jim Neath

Recommend Me

Pages

Archives

Categories

Stalk Me