Resque + God + Capistrano

Attached is a working config to deploy an application with Capistrano that needs to monitor Resque workers with God.

God will run as the deployment user, no need to register it as a system service.

Put this into your config/deploy.rb:

namespace :god do
  def god_is_running
    !capture("#{god_command} status >/dev/null 2>/dev/null || echo 'not running'").start_with?('not running')
  end

  def god_command

...

How to: Store multiple Vim commands in macros and recall them

Vim allows recording a batch of commands as a macro. This is handy if you need to do the same things over and over.

Here is how:

  1. Press q to enter macro mode.
  2. Press a letter (not a number!) key to assign a slot to your macro.
  3. You are now recording. Do whatever you want with usual commands.
  4. Once you are done, press q again to stop recording.
  5. You can now run your recorded macro by pressing @ and its assigned letter key.

Cheats:

  • If you want to run a macro repeatedly, type a number before pressing the @ key. Example: ...

Chosen - makes select boxes better

Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.

Thunderbird: Confirm encryption absence/presence before sending an e-mail

To avoid sending e-mails containing sensitive data unencrypted I strongly suggest you enable a confirmation dialog.

Enigmail can show if the e-mail being sent will be encrypted or not -- and if, which keys will be used. This applies to both clicking the "Send" button or pressing Ctrl+Enter. Thus, you may disable the confirmation for the keyboard shortcut as you get a message box anyways which will avoid sending e-mails by accident.

Instructions

Head over to the Enigmail preferences from the "OpenPGP" menu and tick the corresponding che...

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)

Insert multiple blank rows into an OpenOffice.org/LibreOffice Calc spreadsheet

Select as many rows as you'd like to insert by dragging over the row numbers on the left. Then right-click on any selected row number and select "Insert Rows". Calc will now insert multiple blank rows.

The inserted rows will copy the style from the row above the selection.

This is horrible.

How to diff two strings in Ruby

When you need to use diff in either some Ruby code or your Rails app, use the differ gem.

puts Differ.diff "foo", "boo"
# => {"boo" >> "foo"}

Usage

There are several variants available, all using the base method diff(to, from, separator = "\n").
You have diff_by_line, diff_by_word, diff_by_char and may of course use your own separator:

puts Differ.diff 'Hauptsatz, und mein Nebensatz.', 'Hauptsatz, und dein Nebensatz.', ','
# => Hauptsatz,{" und dein Nebensatz." >> " un...

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.

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...

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.

Web Operations 101 For Developers

This post is not about devops, it's not about lean startups, it's not about web scale, it's not about the cloud, and it's not about continuous deployment. This post is about you, the developer who's main purpose in life has always been to build great web applications. In a pretty traditional world you write code, you write tests for it, you deploy, and you go home. Until now.

Use Capybara on any HTML fragment or page

I think this pattern is really useful not just for upgrading suites from Webrat, but really anywhere you have an HTML fragment or string that you’d like to use Capybara’s matchers on.

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.

Vim: Scroll up/down, keeping your cursor in its row

If you are in the middle of a file and want to scroll, but don't want to move your cursor all the way to the top row, use this:

One line

  • Ctrl+Y → Move viewport down
  • Ctrl+E → Move viewport up (Extra lines)

Half a screen

  • Ctrl+U → Move viewport Up
  • Ctrl+D → Move viewport Down

Those are the default key bindings, they may be different for other layouts/behaviors (like mswin).

Read everything about scrolling in vim in the linked vimdoc.

Thunderbird Addon: Message Archive Options

The addon lets you set the format of the dates used for the year and month folders that the Archive function in Thunderbird 3+ creates. It exposes the (hidden) preference that lets you change the granularity of the folders to either a single folder; an archive folder and a year subfolder; or a month also.

Additionally the addon can add modifiers to the 'A' key shortcut so the key is Shift + A (or Control or Alt).

Hide your Selenium browser window with a VNC server

This is now part of geordi. Please don't follow the instructions below, if you use geordi.

Inspired by the recent headless Selenium note, I found yet another solution for the problem to hide your selenium tests away.

This has the advantages
^

  • not to require a gem (so you do not force this on others)
  • to allow you to take a look at the running webdriver if necessary

Simply make a script th...

Passenger booting Rails 3 application in wrong environment

Passenger gives you the possibility to define in which environment your app should be started.
This has to be added to the VirtualHost configuration for Apache for Rails 2 applications:

RailsEnv development

When running Rails 3, you need

RackEnv development

Firefox 3.6 truncates long tables when printing

Possible fixes:

  • Upgrade your Firefox. It's fixed in 5.0.
  • Hunt down funny float or overflow directives in your CSS.
  • Remove <h1> and <caption> tags in proximity of your table (seriously).

How to look at hidden X screens

When you have a program running in a hidden X screen (like with Xvfb for Selenium tests) you may want to look at that hidden screen occasionally.

First, find out what X displays are currently active:

netstat -nlp | grep X11

This should give you some results like these:

unix  2      [ ACC ]     STREAM     LISTENING     8029600  4086/Xvfb           /tmp/.X11-unix/X99
unix  2      [ ACC ]     STREAM     LISTENING     8616     -     ...

simple_format helper for Javascript

The Javascript code below is a rough equivalent to the simple_format helper that ships with Rails:

function simpleFormat(str) {
  str = str.replace(/\r\n?/, "\n");
  str = $.trim(str);
  if (str.length > 0) {
    str = str.replace(/\n\n+/g, '</p><p>');
    str = str.replace(/\n/g, '<br />');
    str = '<p>' + str + '</p>';
  }
  return str;
}

Unlike the Rails helper, this does not preserve whitespace. You probably don't care.

Resque: Work off queues manually

If you're writing a spec for an application using Resque, you may need to work off queues manually without having an external worker running.

For this, you could use ResqueSpec which basically stubs away Resque completely.

If you don't want that, but more closely mimic what actually happens, use this instead:

module Resque

  def self.work_off(*queues)
    if queues.any? { |queue| peek(queue) }
      worker = Work...