A gem is a simple way to distribute functionality, it can be a small plugin, a Ruby library or sometimes a whole program. Thanks to RubyGems, a gem hosting service, developers have a wide range of gems at their disposal allowing them to easily add functionality to their applications.

But what if there is no gem available that will suit the functionality you need, and you find yourself writing the same code over and over again for different projects? Well, in that case you should consider making your own gem.

It’s considered a good practice to extract a gem out of an existing application, since that way you will have a better understanding of all the requirements as well as how the gem will be used. This blog post will illustrate just that on a real life example, and will take you through the process of creating a slug_converter gem.

For our new project it was necessary to modify the starting id of our database. This can be handled through migration for creating table but we decided to create a rake task that handled this for us.

The rake task that we created detects what database is being used and executes appropriate changes according to that. You can create a rake task using rails generate command for rake task:

If you are using Devise gem for authentication and you have been adding custom fields to your model you’ll get in trouble when you try to create a new instance or update an existing one. All your added fields will be treated as unpermitted. The solution for this problem is to customise Devise’s configure_permited_parameters action. All you need to do is to add this action to your Application controller and push parameters that need to be permitted to devise_paremeter_sanitizer array. So let’s say you have a User Model and you have added company_name and website fields to your user’s table, to permit this parameters on sign_up you need to add this to your Application controller:

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up).push(:company_name, :website)

It is the same principle for the :sign_in and :edit_account. You can see what are default permitted parameters here.

Devise has a very useful Trackable module used to track user’s sign in count, timestamps and IP address. There are some occasions when you need to disable tracking. For example for API requests where user signs in on every request; for instances where admin might sign in as an user; and similar.

To disable Devise Trackable module you need to set request.env["devise.skip_trackable"] = true. You have to do that before trying to authenticate user, so you’ll want to put it in a before_filter, or even better prepend_before_filter to make sure it’s before authentication.

Add this to your controller in which you want to disable tracking:

prepend_before_filter :disable_devise_trackable

  def disable_devise_trackable
    request.env["devise.skip_trackable"] = true

Note to self: here is how to upgrade Ubuntu 8.04 LTS (or any other release that is no longer supported) to newer Ubuntu release.

When you are upgrading unsupported release of Ubuntu if you try to do the usual sudo apt-get update it will most likely fail because… well, it’s unsupported. The simple fix for this is to change your /etc/apt/sources.list and replace repository URLs from something like us.archive.ubuntu.com to old-releases.ubuntu.com.

After that you should be able follow normal upgrade procedure (use sudo if you are not root):

apt-get update
apt-get install update-manager-core


Here is a quick way to setup VirtualBox using Vagrant with Heroku-like box on Mac.

  1. Install VirtualBox from https://www.virtualbox.org/wiki/Downloads

  2. Install Vagrant from http://downloads.vagrantup.com/

  3. Create Vagrantfile for Heroku-like box (based on https://github.com/ejholmes/vagrant-heroku) that looks something like:

Vagrant.configure("2") do |config|
  config.vm.box = "heroku"
  config.vm.box_url = "https://dl.dropboxusercontent.com/s/rnc0p8zl91borei/heroku.box"
  config.vm.synced_folder ".", "/vagrant", :nfs => true
  config.vm.network :private_network, ip: ""  # required for NFS

Beside telling Vagrant to use Heroku-like box from https://github.com/ejholmes/vagrant-heroku it also sets up shared dir between host and VM machine. It will mount Vagrantfile dir (.) to /vagrant in VM.

vagrant up will setup the VM and start it up.

Now you can use vagrant ssh to login to VM.

Vagrant Heroku-like box comes with Postgresql, but if you want you can easily setup sqlite:

sudo apt-get install libsqlite3-dev

Bonus tip: when you are working on multiple projects sometimes you can forget which VMs are running. You can list all running VMs using:

VBoxManage list runningvms

Further reading:

RailsDiff is a very useful site when upgrading Rails versions (for example, from Rails 3.2 to Rails 4). It will generate default Rails app using two different Rails versions and it will compare them. The result is that you can see all the configuration changes (like in application.rb) and all other changes – which is really useful when upgrading to new Rails version.

Assume that you have the usual setup with model (MyFile) using simple Carrierwave uploader (MyFileUploader):

# app/models/my_file.rb
class MyFile < ActiveRecord::Base
  mount_uploader :file, MyFileUploader

To be able to test Carrierwave uploaders with RSpec using FactoryGirl factories you need:

  • define factory with uploaded file
  • modify test environment storage so test file uploads are separated from other uploads
  • turn off image processing to speed up tests
  • perform cleanup after each test

Define factory

# spec/factories/my_files.rb
FactoryGirl.define do
 factory :my_file do
   photo Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/myfiles/myfile.jpg')))

Setup Carrierwave

First we need to make sure Carrierwave is using local file system for storage and to disable file processing for testing environments. Disabling file processing will speed up tests considerably. We can do that by adding following to Carrierwave initializer:

if Rails.env.test? || Rails.env.cucumber?
  CarrierWave.configure do |config|
    config.storage = :file
    config.enable_processing = false

Next we should separate test uploads from any other uploads. We can do that by modifying cache_dir and store_dir methods for all Carrierwave models (i.e. all models that are descendants of CarrierWave::Uploader::Base). So the whole Carrierwave initializer looks something like:

# config/initializers/carrierwave.rb
if Rails.env.test? || Rails.env.cucumber?
  CarrierWave.configure do |config|
    config.storage = :file
    config.enable_processing = false

  # make sure our uploader is auto-loaded

  # use different dirs when testing
  CarrierWave::Uploader::Base.descendants.each do |klass|
    next if klass.anonymous?
    klass.class_eval do
      def cache_dir

      def store_dir

Clean up uploaded files

Using factory defined above will create uploaded files in cache_dir and store_dir. These are just temporary files and should be removed after each test, so each of them has a clean slate. By adding after :each hook in RSpec configuration block we can remove these files simply by deleting spec/support/uploads dir.

# spec_helper.rb
RSpec.configure do |config|
  config.after(:each) do
    if Rails.env.test? || Rails.env.cucumber?

Here are some random Rails tips I’ve found useful:

  • rails console sandbox – if you open console like this it will rollback all database changes once you exit. Pretty useful for playing around without making any changes to database.
  • rake db:migrate:status – useful when you want to see the status of current database. It will show the status of all migrations.
  • User.pluck(:email) – since Rails 3.2.1 you can use pluck method to get an array of values in one particular column. It’s the equvivalent of doing User.select(:email).map(&:email)

Setting up Paperclip to use Amazon’s S3 is as simple as setting :storage => :s3 and providing right credentials to Paperclip by setting :s3_credentials option. Best way to provide S3 credentials is to use an YML file (usually config/s3.yml) which allows you to set different credentials for each environment. For example:

# config/s3.yml
  access_key_id: XYZXYZXYZ
  secret_access_key: XYZXYZXYZ
  bucket: mygreatapp-development
  access_key_id: XYZXYZXYZ
  secret_access_key: XYZXYZXYZ
  bucket: mygreatapp-production

Of course you want to treat s3.yml same as database.yml – i.e. you don’t want to track it with git and you want for each person/server to have it’s own.

However, consider this: you are working on Open Source app in a public git repository and you are deploying it on Heroku. Heroku doesn’t allow you to create files (unless they are in git repository) and you can’t commit s3.yml with your credentials to public repository.

One solution is to define different :s3_credentials hash in one of the environment files or to load different YML file for each environment and generate hash from it. Downside is that you need to have a separate YML file for each environment and/or you need to convert YML to hash. Other solution could be to have separate local branch from which you will push to Heroku. Problem with this is that you have to have a local branch for deploying. This means if there are multiple developers who deploy to production each should have separate local branch.

Much simpler way to deploy Paperclip with different S3 credentials for each environment (with one of the environment being deployed on Heroku; and repository being public) is to create s3.yml file as usual (and don’t commit it to git), but define values only for local environment.

For production deployment on Heroku you can write initializer which will set :s3_credentials from ENV variables.

# initializers/s3.rb
if Rails.env == "production"
  # set credentials from ENV hash
  S3_CREDENTIALS = { :access_key_id => ENV['S3_KEY'], :secret_access_key => ENV['S3_SECRET'], :bucket => "sharedearth-production"}
  # get credentials from YML file
  S3_CREDENTIALS = Rails.root.join("config/s3.yml")

# in your model
has_attached_file :photo, :storage => :s3, :s3_credentials => S3_CREDENTIALS

and you can easily set persistant ENV vars on Heroku with:

$ heroku config:add S3_KEY=XYZXYZ S3_SECRET=XYZXYZ

(according to Heroku docs)