Ruby: Natural sort strings with Umlauts and other funny characters

Why string sorting sucks in vanilla Ruby

Ruby's sort method doesn't work as expected with special characters (like German umlauts):

["Schwertner", "Schöler"].sort
# => ["Schwertner", "Schöler"] # you probably expected ["Schöler", "Schwertner"]

Also numbers in strings will be sorted character by character which you probably don't want:

["1", "2", "11"].sort
# => ["1", "11", "2"] # you probably expected ["1", "2", "11"]

Also the sorting is case sensitive:

...

archan937/ruby-mass

Introspect the Ruby Heap by indexing, counting, locating references to and detaching (in order to release) objects.

Geordi: Use load-dump script to source a database dump into your database

This script loads a dump into your development database.

You can provide the full path to you database dump like this:

load-dump path/to/my.dump

When you call load-dump without any arguments it will show a menu with all dumps in your ~/dumps/ folder.

load-dump

This script is part of our geordi gem on github.

Rails asset pipeline: Why relative paths can work in development, but break in production

The problem

When using the asset pipeline your assets (images, javascripts, stylesheets, fonts) live in folders inside app:

app/assets/fonts
app/assets/images
app/assets/javascripts
app/assets/stylesheets

With the asset pipeline, you can use the full power of Ruby to generate assets. E.g. you can have ERB tags in your Javascript. Or you can have an ERB template which generates Haml which generates HTML. You can chain as many preprocessors as you want.

When you deploy, Rails runs assets:precompile...

Random numbers in Ruby

A collection of snippets to generate random number under certain conditions, as:

  • gaussian
  • with a specified distribution
  • triangular distribution
  • ... and some more

Plotting graphs in Ruby with Gruff

Geoffrey Grosenbach has created Gruff for easily plotting graphs. It is written in pure Ruby and integrates with Rails applications.

It provides features as automatic sizing of dots and lines (the more values, the thinner the graph's elements), custom or predefined themes, different styles (bar, line, dot and many more) and multiple graphs in one chart.

Installation

In your Gemfile:

gem 'rmagick', :require => false
gem 'gruff'

Then run bundle install (and don't forget to restart your development server.)

Usage

This i...

The Ruby Toolbox – a collection of good gems

If you need a gem for a certain purpose, be sure to check this site.


The rankings are determined by counting up the number of forks and watchers of various github projects, so I'd view it less as "this is what I should be using," and more as "these are some things I should check out." At the very least, they're all likely to be under active development and fairly up to date, and it's very useful to see groups of gems broken down by category.

Mysterious "margin" below an image

Consider the following HTML & CSS:

<div><img src='http://makandra.com/images/makandra-ruby-on-rails.png' /></div>

^
img {
background-color: red;
}
div {
border: 1px solid black;
}

This will leave a margin of about 5px between the lower edge of the image and the containing div, although there are no paddings or margins set, and there's no whitespace. The reason is, the image will vertically align baseline, and the space below the image is just kept for descenders (the part of letters below the basel...

Guide to localizing a Rails application

Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.

When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.

Static text

  • Static strings and template text in app must be translated: Screens, mailer templates, PDF templates, helpe...

RubyMine: Set specific Ruby version per project

If your project uses another version than your default Ruby, RubyMine will give you incorrect inspections, for example.\
Here is how to switch which Ruby you use in RubyMine.

  1. File → Settings (Or press Ctrl+Alt+S)
  2. Select "Ruby SDK and Gems" from the left pane
  3. Switch your "Ruby interpreter".

Though it may seem you are changing a global setting here, this is in fact a per-project setting, as are all things you change in the "Project Settings [your_project_name]" area of the global settings dialog.

When you switch to another proje...

Fix capistrano errors: "no such file to load -- net/ssh/authentication/agent/socket" or "uninitialized constant Net::SSH::KnownHosts::SUPPORTED_TYPE"

There is a conflict between current capistrano versions and the 2.5.1 net-ssh gem. Make sure you upgrade to 2.5.2, then it should work again.

Bundle capistrano

Capistrano recently had some API changes that can results in deploys not working when running with old deploy.rb files.

So let's bundle it. Put capistrano into your Gemfile, like this:

# Gemfile

group :deploy do
  gem 'capistrano'
  gem 'capistrano_colors'
end

It's possible you need to do a bundle update net-ssh to get things running.

Now double check that all your custom hooks are actually still called. One candidate might be an after deploy:symlink hook that has been renamed into `after deploy:creat...

How to use pessimistic row locks with ActiveRecord

When requests arrive at the application servers simultaneously, weird things can happen. Sometimes, this can also happen if a user double-clicks on a button, for example.

This often leads to problems, as two object instances are modified in parallel maybe by different code and one of the requests writes the results to the database.

In case you want to make sure that only one of the requests "wins", i.e. one of the requests is fully executed and completed while the other one at least has to wait for the first request to be completed, you ha...

Aspect Oriented Programming in Ruby

Slides presenting ways to integrate the ideas of Aspect-Oriented Programming in Ruby.

Outline

  • Why Aspect-Oriented Programming?
  • AOP in Java and AspectJ (a Review).
  • AOP in Ruby.
    • What you can do today.
    • Example AOP-isms in Ruby on Rails.
  • Aspect-Oriented Design.
  • The AOP Promise for Tomorrow.

Fix error: can’t find executable rails

If you get an error like this ...

 can’t find executable rails for rails-3.2.3 (Gem::Exception)

... one of several things might be wrong.

  1. You're using RVM

It's possible that you have a system-wide gem executable (like rails) that requires a gem that is not available in the current RVM Ruby or gemset. Check what Ruby you are using (rvm current) and look out for .rvmrc files in your current directory (which change your Ruby upon entering the directory).

  1. You killed a gem install process
    ----------...

OCRA

OCRA (One-Click Ruby Application) builds Windows executables from Ruby source code. The executable is a self-extracting, self-running executable that contains the Ruby interpreter, your source code and any additionally needed ruby libraries or DLL.

ocra [option] script.rb

Will package “script.rb“, the Ruby interpreter and all dependencies (gems and DLLs) into an executable named “script.exe“.

salesking/king_dtaus

DTAUS & DTAZV are formats for German bank transfers and is short for "Datenträgeraustausch". The format itself totally sucks because it was established in the last century, to be used on floppy disks. Still almost all German banks use it (they only seem innovative at robbing), and it is therefore supported in common banking programs too.

This gem saves you all the trouble when generating DTAUS- or DTAZV-text.

Navigating through the browser history in a cucumber feature using selenium

In order to navigate through the browser history. you can manipulate the window.history object via javascript like follows:

When /^I go back in the browser history$/ do
  page.evaluate_script('window.history.back()')
end 

For further functions of the window and history objects check out this link.


An improved version of this step is now part of our gem spreewald on Github.

Authorize allowed values with assignable_values

All our projects have enum-like requirements like this:

  • An attribute value must be included in a given set of values.
  • The list of allowed values must be retrievable in order to render <select> boxes.
  • Each value has a humanized label.
  • Sometimes there is a default value.

Most of the time, this requirement is also needed:

  • The list of assignable values depends on the user who is currently signed in.

In our past projects there are many different solutions for these related requirements, e.g. ChoiceTrait, methods like `available_...

Convert primitive Ruby structures into Javascript

Controller responses often include Javascript code that contains values from Ruby variables. E.g. you want to call a Javascript function foo(...) with the argument stored in the Ruby variable @foo. You can do this by using ERB tags (<%= ruby_expression %>) or, in Haml, interpolation syntax (#{ruby_expression}).

In any case you will take care of proper quoting and escaping of quotes, line feeds, etc. A convenient way to do this is to use Object#json, which is defined for Ruby strings, numb...

How to fix Passenger "Unexpected end-of-file detected" error

This is for you if Passenger gives you the following useless error message.

Passenger encountered the following error:\
The application spawner server exited unexpectedly: Unexpected end-of-file detected.

Exception class:
PhusionPassenger::Rack::ApplicationSpawner::Error

Most often this happens because you are missing a gem. Usually Passenger would tell you about that but in some cases it can't.

To resolve this issue, run:

bundle install

If this does not do the trick for you, take a look at the Apache log files for de...

Building Gem 'RedCloth' with Bundler and GCC 4.6

If you cannot install the gem 'RedCloth' via bundle install you might want to try the following.

Specifying extra build options for bundler which will only be applied when building RedCloth:

bundle config build.RedCloth --with-cflags=-w

Shell script to deploy changes to production and not shoot yourself in the foot

Geordi, our collection of command line tools, has been extended by another command deploy-to-production. This script encapsulates the following workflow:

  • Pull the production branch.
  • Show which commits from the master would make it to production with this deploy.
  • Ask if you want to proceed.
  • If yes, merge the master into the production branch, push and deploy with bundle exec cap production deploy:migrations

The script will ask you for the names of your master branch, production branch an...

Fix warning: Cucumber-rails required outside of env.rb

After installing Bundler 1.1 you will get the following warning when running tests:

WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being defered until env.rb is called.\
To avoid this warning, move 'gem cucumber-rails' under only group :test in your Gemfile

The warning is misleading because it has nothing to do with moving cucumber-rails into a :test group. Instead you need to change your Gemfile to say:

gem 'cucumber-rails', :require => false