Jim Neath

Manchester based Ruby on Rails & Facebook App Developer

Showing blog posts tagged as "Plugins"

Optimizing your MySQL queries and performance in your rails applicationcan be a real pain. The plugins below help to make things a little easier.

Bullet

Bullet is a rails plugin, written by Richard Huang (@flyerhzm), that helps to kill N+1 queries. It shows you where you should be using :include in your ActiveRecord calls. Bullet also informs you where you’re missing counter caches as well as warning you of any unused eager loading.

http://github.com/flyerhzm/bullet/

SlimScrooge

SlimScrooge is a plugin by Stephen Sykes (@sdsykes), that restricts the columns retrieved in your MySQL queries by learning which attributes are subsequently called on the ActiveRecord model.

Below is an example, taken from the readme:

# 1st request, sql is unchanged but columns accesses are recorded
Brochure Load SlimScrooged 1st time (27.1ms)   SELECT * FROM `brochures` WHERE (expires_at IS NULL)

# 2nd request, only fetch columns that were used the first time
Brochure Load SlimScrooged (4.5ms)   SELECT `brochures`.expires_at,`brochures`.operator_id,`brochures`.id FROM 
`brochures` WHERE (expires_at IS NULL)

# 2nd request, later in code we need another column which causes a reload of all remaining columns
Brochure Reload SlimScrooged (0.6ms) `brochures`.name,`brochures`.comment,`brochures`.image_height,`brochures`.id,
`brochures`.tel,`brochures`.long_comment,`brochures`.image_name,`brochures`.image_width FROM 
`brochures` WHERE `brochures`.id IN ('5646','5476','4562','3456','4567','7355')

# 3rd request
Brochure Load SlimScrooged (4.5ms)   SELECT `brochures`.expires_at,`brochures`.operator_id,`brochures`.name,
`brochures`.id FROM `brochures` WHERE (expires_at IS NULL)

http://github.com/sdsykes/slim_scrooge/

Query Reviewer

Query Reviewer by David Stevenson (@dsboulder) of Pivotal Labs, is a Rails plugin that adds a div to the top left of the screen that contains lots of useful details regarding the MySQL executed on the current page.

The plugin makes it easy to view the EXPLAIN output for each SELECT query on the page. It also provides ratings and warnings on each query executed on a page.

Query Reviewer

http://github.com/dsboulder/query_reviewer

Rails Indexes

Rails Indexes is a plugin by Elad Meidar (@eladmeidar), that helps to generate a migration containing suggested indexes for your database.

By running the following rake command:

rake db:index_migration

Rails Indexes will generate the example migration containing suggested indexes. While these indexes are a good start, you will probably find that you need some detailed database indexes.

http://github.com/eladmeidar/rails_indexes/

Ambitious Query Indexer

Ambitious Query Indexer is an index generating plugin by Sam Phillips (@samsworldofno). Like Rails Indexes, it generates a migration containing suggested indexes, but it works by analysing all of the queries it can find in your app.

http://github.com/samdanavia/ambitious_query_indexer

Note: MailStyle was originally called Shemail but was changed due to a general negative response to the name from the public.

Background

Writing inline styles for HTML emails is dull and boring but unfortunately a necessary evil. Rather than do it by hand we thought it would be nicer to let our app do it for us. So we wrote MailStyle.

Enter MailStyle

MailStyle allows you to write the css for your html emails as you normally would, then writes the styles inline when you send your emails. It also makes sure that your image paths are absolute rather than relative.

Installation

First install the dependencies:

sudo gem install nokogiri css_parser

Then install MailStyle to your rails app:

script/plugin install http://github.com/purify/mail_style

Usage

Rendering CSS Inline

Simply add the css method to your deliver actions:

class Notifier < ActionMailer::Base
  def welcome_email
    css :email

    subject 'Welcome Aboard'
    recipients 'someone@example.com'
    from 'jimneath@googlemail.com'
    sent_on Time.now
  end
end

This will look for a css file called email.css in your public/stylesheets folder. The css method can take either a string or a symbol. You can also pass the css file name with or without the .css extension.

MailStyle will now write the styles from email.css into html part of the welcome email (eg. welcome_email.text.html.erb). It won’t touch the plain text part, neither will it do anything if you’re only sending a single part email (eg. welcome_email.html.erb). You shouldn’t be sending html emails without a plain text version anyway.

Say that our email.css file looks like the following:

body { background: #000 }
p { color: #f00; line-height: 1.5 }
.text { font-size: 14px }

And our welcome_email.text.html.erb looks like this:

<p class="text">Hello World</p>

Then the resulting html that will be sent out will resemble the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <body style="background: #000">
    <p style="color: #f00;line-height:1.5;font-size: 14px">Hello World</p>
  </body>
</html>

Fixing Image URLs

If you have default_url_options:host set in your mailer, then MailStyle will do it’s best to make the urls of images absolute.

In your mailer
ActionMailer::Base.default_url_options[:host] = "example.com"
Example CSS
p { background-image: url(../images/chunky-bacon.png) }
Example HTML View
<img src="/images/header.jpg">
<p>Hello World</p>
Example Output
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
    <img src="http://example.com/images/header.jpg">
    <p style="background-image: url(http://example.com/images/chunky-bacon.png)">Hello World</p>
  </body>
</html>

How You Can Help

The main issue at the moment is speed, so any help speeding things up would be awesome. As always, you can fork the repo at Github.

Further Reading

Below are a couple of links you may find useful regarding HTML emails:

ThinkingSphinx and Nil Results

Have you ever gotten a result like the following when using ThinkingSphinx (by the awesome Pat Allen):

NoMethodError (undefined method `constantize' for nil:NilClass):

This error occurs when your index isn’t quite up to date and ThinkingSphinx returns results that have since been deleted from your database. To fix the problem add :retry_stale => true to your searches, like this:

Article.search('chunky bacon', :retry_stale => true)

There is more information about :retry_stale in the source code:

# If you pass :retry_stale => true to a single-model search, missing records will
# cause Thinking Sphinx to retry the query but excluding those records. Since search
# is paginated, the new search could potentially include missing records as well, so by
# default Thinking Sphinx will retry three times. Pass :retry_stale => 5 to retry five
# times, and so on. If there are still missing ids on the last retry, they are
# shown as nils.

I hope this saves someone a few minutes in the future :)

Creating PDF Documents in Ruby on Rails

Those of you that follow me on Twitter will probably know that I’ve spent the last week or so trying to find a decent way of generating PDF documents from a Rails application. I finally found a solution that suited my needs so I thought I’d share it with you lovely people.

Initial Probing

After my first round of googling I came across 2 solutions that people seem to be using:

I’ll admit I didn’t really look too much into PDF::Writer but I did spend a couple of days playing around with Prawn.

All was going well until I ran into certain situations. The two main problems I had with Prawn were that it’s too difficult to style things as I wanted to and generating a table of contents. I might be missing something but I couldn’t get my head around how to solve the latter.

I don’t want to learn a new syntax to define my PDF documents. I don’t want to learn a new way of styling things. I like my HTML and CSS.

WHERE’S MY HTML AND CSS?!

Introducing Prince

Prince XML is a command line program that takes your spiffy html and css and returns a nicely formatted PDF document for you.

Prince is a computer program that converts XML and HTML into PDF documents. Prince can read many XML formats, including XHTML and SVG. Prince formats documents according to style sheets written in CSS.

See, I told you.

So, we’ve got prince xml, but what about hooking it up with rails?

Introducing Princely

Princely is a fantastic plugin by Michael Bleigh, author of other great plugins, such as subdomain-fu and acts-as-taggable-on.

Princely is basically a wrapper around the Prince API. It allows you to define your PDF views as templates like show.pdf.erb. You can write your views as you would normal html views and Princely will return a pdf when you hit those pages.

def show
  respond_to do |format|
    format.html
    format.pdf do
      render :pdf => "filename", :stylesheets => ["application", "prince"], :layout => "pdf"
    end
  end
end

Awesome, right?

Installing Prince and Princely

To install Prince XML, visit the download page and chose the package which suits your needs. Done.

Next, to install Princely, run the following command from your Rails app.

script/plugin install git://github.com/mbleigh/princely.git

Page Numbering

To set the page numbers of you PDFs you’ll need to use the counter attribute of CSS3.

@page {
  @bottom-left {
    content: counter(page);
  }
}

This snippet of code will, funnily enough, add the current page number to the bottom left of each page. That’s all there is to it.

If you’d prefer to show the page number along with the total number of pages, you can use the following:

@page {
  @bottom-left {
    content: "Page " counter(page) " of " counter(pages);
  }
}

Table of Contents

If you’re creating a large PDF with a few sections, it’s generally a good idea to include a table of contents at the start of your document.

The first thing you need to do, is output a list of links at the start of you document that link to internal anchors:

<ul id="toc">
  <li><a href="#ruby">Chapter 1: An Introduction to Ruby</a></li>
  <li><a href="#rails">Chapter 2: Hello, Rails!</a></li>
  <li><a href="#prince">Chapter 3: Pump it up, Prince!</a></li>
</ul>

This will give you a list, that looks something along the lines of the following image:

toc

Now with a bit of CSS magic, we can add the page numbers from our PDF to the table of contents. Ready for this? Go!

ul#toc a::after
{
  content: leader('.') target-counter(attr(href), page);
}

That’s it. attr(href) finds the target of the link. target-counter finds the page that the anchor is on and the leader call just pads the left had side with periods. Win.

That nifty bit of CSS should leave you with something looking like this:

toc unstyled

A bit more CSS to tidy it up a bit:

ul#toc ul {
	margin: 0;
	list-style: none;
	padding: 0;
}

ul#toc a {
	text-decoration: none;
}

ul#toc li {
	margin: 0;
	padding: 0;
	list-style: none;
}

And then we should have something that looks a bit nicer:

toc styled

That’s all there is to it. Easy, right?

Metadata

Prince writes metadata to your PDFs via the meta tags in your html. You can set the document author, subject and keywords using the following:

<head>
  <title>PDF Generation</title>
  <meta name="author" content="Jim Neath"/>
  <meta name="subject" content="Generating PDFs with Prince"/>
  <meta name="keywords" content="PDF, prince, ruby, rails"/>
</head>

Further Reading

Speeding Up Rails Development

Over the last few months I’ve realised that the speed at which I develop new projects is a lot quicker than it used to be. So I thought I’d share some of the things I’ve learned and also some quite obvious things (to me at least).

Use a Base Application

I’m obviously going to be horrifically biased due to the fact that I helped to develop Bort, but I think that base apps are the way to roll. They save you about half a days worth of development and let you get straight into developing your application rather than fucking around doing the same monotonous stuff every time.

So here’s a run down of base apps floating around:

I haven’t used any of these apart from Bort, so I can’t really give you any opinion but everything I’ve seen by Thoughtbot and James Golick have always been awesome. Just look through them and find which one suits your needs.

I would like to end this section with a nice graph taken from Rails Rumble Observations, part II :)

Write Your Own Scaffold Generator

The default Rails scaffold generator is alright for prototyping an app but let’s face it, you wouldn’t use it for everything. So why don’t you made your own that you can use for everything. At the start of the last project we worked on, we spent 2-3 days working on a scaffold generator that would help to generate parts of the admin.

We made the generator generate all the search stuff, add sortable tables, generate basic specs and a whole bunch of other awesome stuff. Now we can get an awesome admin section set up for a model by running line from terminal.

This must have saved us at least a weeks worth of time. Time that we can now spend making sure that the rest of the site is as brilliant as possible. With the extra time, you take it easy, or you could add extra features, improve the UI, whatever. Keep it RESTful, kids.

Use a Form Builder

I hate forms. No secret there. But alas, nearly every application you’ll develop need to have forms. I wrote a custom form builder for the chaps at Fudge and it saves us a hell of a lot of time.

Now instead of writing something like the following:

<% form_for @story do |f| %>
  <%= f.error_messages %>
  <fieldset>
    <legend>Story Details</legend>
    <ol>
      <li>
        <%= f.label :title %>
        <%= f.text_field :title %>
      </li>
      <li>
        <%= f.label :body, 'Content' %>
        <%= f.text_area :body %>
      </li>
    </ol>
    <div class="buttons">
      <%= f.submit 'Create' %>
    </div>
  </fieldset>
<% end %>

Using our form builder we write:

<% form_for @story do |f| %>
  <%= f.error_messages %>
  <% f.field_set "Story Details" do %>
    <%= f.text_field :title %>
    <%= f.text_area :body, :label => 'Content' %>
  <% end %>
  <%= f.submit 'Create' %>
<% end %>

Now imagine you’re got to write close to 50 forms for an application. Can you guess which ones saves you time? Which one is more enjoyable to use? You got it.

Now while I wouldn’t say our form builder is ready for the general coding public (it isn’t), there are still a few out there.

I have used Semantic Form Builder by RubyPond before and it also happens to be the one we based out form builder on.

Build a Populate Rake Task

We started using Populator/Faker a couple of months a go and this is probably one of our biggest time savers. It’s a pain in the ass adding test data into your applications.

Ryan Bates has made a great railscast on how to use Populator along with Faker to generate fake datausing a rake task so I’ll leave it to his awesome video to tell you all about it.

There are also a couple other options out there for generating fake data, the random-data gem and the Forgery plugin.

Peter Cooper has a more thorough run down of all three options over at Rails Inside.

Use Plugins/Gems

This should really go without saying, but I’ve seen a few people trying to write (poor) code for tasks that have already been solved, tested and improved on.

Gems and plugins are probably your biggest time saver. One of the things I love about the ruby community is that a lot of people give back to it.

If you have a problem, have a look on the awesome GitHub and see if there’s a plugin/gem floating around that looks like it could solve your problem. Try it out. If it works brilliant, if not see if you can fix it and improve the original code. Then if someone else has the same problem, they can use the plugin. If everyone helps out, we all have an easier job, we can do less work and enjoy life more.

Seriously, Just Buy a Fucking Mac

Just do it. Stop making excuses. I was a Windows user for about ten years but mainly because I didn’t know any better. I now work full time on a mac, both at home and at work, and there’s not a thing you could do to make me go back to Windows.

Windows simply won’t do a lot of things that you’ll want to do. Background jobs? Not a chance. Git? oh yeah, you can use msysgit but who the fuck wants to open up a separate program just to use git? Fuck off Windows. You’re slow and you suck.

Why get a mac? Rails runs faster. You can use the best text editor around, TextMate. You can install all those gems and plugins that all say: “This won’t work on Windows”.

Think getting a mac is too expensive? Get a low spec mac mini for $599. That’s what I started using and even though it’s low spec I never had a problem with it. You can use your USB keyboard, mouse and your monitor from your Windows machine. Still think it’s too much? Have a look on Amazon…

So do you, my lovely readers, have any more suggestions/tips to speed up your development?

Getting the Dimensions of a Flash (SWF) File

This is a just a quick post that will hopefully save some people a hell of a lot of time.

If you’re trying to get the width and height of a flash file, a banner for example, then you can use the ImageSpec library by Brandon Anderson.

You can checkout the code with the following:

svn checkout http://ruby-imagespec.googlecode.com/svn/trunk/ vendor/plugins/ruby-imagespec

Then call it in your code to get the dimensions of a flash movie. Say you’re using Paperclip, then you could do the following:

dimensions = ImageSpec::Dimensions.new(@banner.file.path)
dimension.height # Get the height
dimesions.width # Get the width

Rad.

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.

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.

Rails Hosting

Once you’ve got your wonderful social network finished, you’re going to want somewhere to host the beast.

I highly recommend checking out Brightbox for all your hosting needs. They offer affordable servers complete with Five Runs.

Paperclip: Attaching Files in Rails

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 separate model (thank god). Your attachments are treated just like any other attribute. 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 Validations

At the moment Paperclip has two different validation types, validates_attachment_presence and validates_attachment_content_type.

validates_attachment_presence

validates_attachment_presence gives your ActiveRecord style validations to check to see if your paperclip model has an attachment present.

validates_attachment_presence :avatar

validates_attachment_content_type

validates_attachment_content_type lets your check the type of file that has been uploaded by checking it’s mime type.

validates_attachment_content_type :avatar, :content_type => 'image/jpeg'

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.

I am available for freelance work! Click here to email me.

Jim Neath is a Freelance Ruby on Rails & Facebook app developer from Manchester, UK, currently working for Engine Yard.