Webrat doesn't follow redirect because it considers the url external

Rails doesn't know which host it is running on. For generating links, it strips the hostname off the request URL, which can lead to errors when you have absolute URLs in your Cucumber tests.

If you really need to use absolute URLs somewhere, say in an email you send, either throw away the host when parsing it (e.g. body.scan(/http:\/\/[^\/]+\/([^\s"<]+)/)) or tell Webrat you're back on your site.

Ruby GetText will eval scripts containing ActiveRecord classes

When the Ruby parser module of Ruby-GetText comes across a file in one of its search directories (e.g. lib/scripts/) and finds out that you are defining ActiveRecord classes inside it, it evaluates the whole file. Here is how to avoid that.

What's happening?

Let's say you have the following script which is only run once, manually, via script/runner:

# lib/scripts/doomsday.rb
class User < ActiveRecord::Base; end
User.destroy_all

In that case we ...

Capybara - The missing API

The Capybara API is somewhat hard for parse for a list of methods you can call on a Capybara node. Below you can find such a list. It's all copied from the Capybara docs, so all credit goes to the Capybara committers.

When you talk to Capybara from a Cucumber step definition, you always have page as the document root node, or whatever you scoped to by saying within(selector) { ... }. You can select child notes by calling page.find(selector) or page.all(selector). You can call the same ...

Always store your Paperclip attachments in a separate folder per environment

tl;dr: Always have your attachment path start with :rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/.


The directory where you save your Paperclip attachments should not look like this:

storage/photos/1/...
storage/photos/2/...
storage/photos/3/...
storage/attachments/1/...
storage/attachments/2/...

The problem with this is that multiple environments (at least development and test) will share the same directory structure. This will cause you pain eventually. Files will get overwritten and...

Nginx Error "413 Request Entity Too Large"

If you get the error "413 Request Entity Too Large" from Nginx client_max_body_size is too low (default is client_max_body_size=1m).

This can happen for example during file upload.

Check whether a Paperclip attachment exists

Don't simply test for the presence of the magic Paperclip attribute, it will return a paperclip Attachment object and thus always be true:

- if user.photo.present? # always true
  = image_tag(user.photo.url)

Use #exists? instead:

- if user.photo.exists?
  = image_tag(user.photo.url)

JSONP - Wikipedia

Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code.

Cross-Origin Resource Sharing - Wikipedia

Cross-Origin Resource Sharing (CORS) is a browser technology specification, which defines ways for a web service to provide interfaces for sandboxed scripts coming from a different domain under same origin policy. CORS is a modern alternative to the JSONP pattern. While JSONP supports only the GET request method, CORS also supports other types of HTTP requests. Using CORS enables a web programmer to use regular XMLHttpRequest which supports better error handling than JSONP. On the other hand, JSONP works on legacy browsers that do not have C...

Responding to the OPTIONS HTTP method request in Rails: Getting around the Same Origin Policy

Code example for implementing Cross-Origin Resource Sharing (CORS) in Rails.

Zip files with Ruby

When you need to zip up files in Ruby, use zipruby.

sudo gem install zipruby

You can add existing files, add files from strings and even add directories.
Example usage:

require 'zipruby'
cars = %w[audi bmw mercedes]

zipfile = Tempfile.new('my.zip', 'tmp')
Zip::Archive.open(zipfile.path, Zip::CREATE) do |zip|
  zip.add_file '/tmp/me.txt'
  zip.add_dir 'cars' 

  cars.each do |car|
    zip.add_buffer "cars/#{car}.txt", "This #{car} is mine!" 
  end
end

Credits go to winebarrel for the Ruby bin...

Downloading files from Ruby on Rails

To offer files for download, use send_file.

def download(file)
  send_file file.path, :disposition => 'attachment'
end

Note that a send_file replaces the default :render action.

Resque: Clearance authentication for dashboard

Resque comes with its own dashboard (Resque server) that you can mount inside your Rails 3 application with

#config/routes.rb:

require 'resque/server'

My::Application.routes.draw do
  # ...

  mount Resque::Server => '/resque'
end

Unfortunately, since this bypasses the filters in your ApplicationController, everyone can access this dashboard now (unless you have some Rack-based authentication in place, like Devise).

If you're using ...

Delete a Clearance session after some time of inactivity

This note describes how to kick a user out of a Rails application after she hasn't requested an action for a while. Note that this is different from deleting sessions some time after the last login, which is the default.

Also note that this is probably a bad idea. Most sites keep sessions alive forever because having to sign in again and again is quite inconvenient for users and makes your conversion rates go down the toilet. [The Clearance default is to keep sessions around for one year](https://makandracards.com/makandra/701-when-sessio...

Rails 3: Sending tempfiles for download

When you create a temporary file (e.g. to store a generated Excel sheet) and try to send it to the browser from a controller, it won't work by default. Take this controller action:

class FoosController < ApplicationController
  def download
    file = Tempfile.new('foo')
    file.puts 'foo'
    file.close
    send_file file.path
  end
end

Accessing this controller action will usually raise a 404 not found in the browser and the Apache log will say:

The given path was above the root path: xsendfile: ...

url_for with added params

You cannot say this because url_for only takes one parameter:

url_for(@deal, :tab => 'general') # won't work

Just use polymorphic_url instead:

polymorphic_url(@deal, :tab => 'general')

Shell script to generate a Git commit with Pivotal Tracker story ID and title

We usually generate our commit messages from Pivotal Tracker IDs and titles, like
[#15775609] Index view for conflicts

The geordi command commit automates this. (See: Pretty Commit messages via geordi).

Just run geordi commit and it will connect to PT and let you select from a list of all started and finishes stories. Then it runs git commit with the generated message (i.e. all staged changes will be commited).

When running for the first time, Geordi will request your PT...

Configuring ActionMailer host and protocol for URL generation

When you generate a URL in a mailer view, ActionMailer will raise an error unless you previously configured it which hostname to use.

There are two options to set the default_url_options of ActionMailer:

  1. Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs)
  2. Dynamic solution

1. Hardcoded solution

When you are sending mails from outside the request cycle, e.g. ActiveJob/Sidekiq or Cronjobs, y...

Getting non-Aero toolbars for Thunderbird 5 on Windows 7

Thunderbird 5 brings a custom chrome on Windows Vista/7 that uses translucent Aero decorations on toolbars and menubars. Here is how to restore solid backgrounds if you don't like it.

Put the following into chrome\userChrome.css in your Thunderbird profile directory:

@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
window {
  background-color: -moz-dialog !important;
}

(Re-)start Thunderbird afterwards.


If you need more info on where the userChrome.css is suppose...

Run Selenium tests in Chrome instead of Firefox

Here is how to switch your Selenium to Chrome:

  1. Make sure you've got a recent version of chromedriver in your $PATH

See also geordi chromedriver_update which is automatically executed before every usage of geordi cucumber.

  1. Register Driver:

Create a file features/support/capybara.rb with the following content for recent version of Capybara:

Capybara.register_driver :selenium do |app|
  Capyb...

How to fix: undefined method `specifications' (caused by RubyGems 1.8)

Sometimes, when running a rake task, RubyGems 1.8.5 raises an error:

rake aborted!
undefined method `specifications' for "/usr/lib/ruby/gems/1.8":String

This has been fixed since May 31 but is still not available as a new RubyGems version.

Either wait for a new version to eventually come out, downgrade to some really old version (1.6.2 works for some) or apply the fix manually:

  • Find your rubygems.rb -- mine was located at `/usr/local/lib/sit...

markbates/coffeebeans

When CoffeeScript was added to Rails 3.1 they forgot one very important part, the ability to use it when responding to JavaScript (JS) requests!

In Rails 3.1 it’s incredibly easy to build your application’s JavaScript using CoffeeScript, however if you fire off an AJAX request to your application you can only write your response using regular JavaScript and not CoffeeScript, at least until CoffeeBeans came along.

How to use Git on Windows with PuTTY

  1. Get "PuTTY Link" and "Pageant" (an SSH key agent) from the PuTTY download page.

  2. Run pageant.exe, find its icon inside your system tray and add your SSH key.

  3. Open up a cmd and put the full path to PuTTY's plink.exe into the GIT_SSH environment variable, e.g.:

    set GIT_SSH=D:\PuTTY\plink.exe
    

You can then use Git like you would on any sane operating system. Just go ahead and git clone, git pull, etc.

Also, you may want to add the environment vari...

Order in which RSpec processes .rb files

Because your examples should not change global state, you should not need to care about the order in which RSpec processes your .rb files. However, in some cases you might want to know.

RSpec 3

  • Runs .rb files in alphabetical order of their file paths by default (or when you specify --order defined).
  • You run t...

SSL: Build a Certificate signing request (CSR)

In order to request a SSL certificate from any dealer, you usually need a CSR certificate. As both the CSR as well as key are created in this step, make sure you save this certificate on a trusted, secure machine only. Usually this is your production environment.

Run this on the server (not on your machine) as root.\
Replace your-domain.tld with the domain you request the certificate for and YYYY with the current year so you will not have any conflicts when requesting a certificate next year.

openssl req -new -sha256 -out www.your-dom...