Ruby: Indent a string

Copy the attached file to config/initializers/indent_string.rb and you can say

"foo".indent(4) # "    foo"

Note you will find many simpler implementations of this method on the Interweb. They probably won't do what you want in edge cases, fuck up trailing whitespace, etc. The implementation in this card has the following behavior:

describe '#indent' do

  it 'should indent the string by the given number of spaces' do
    "foo".indent(2).should == "  foo"
  end

  it 'should indent multiple lines line by line' do

...

New cards feature: Cite other cards

We've made it easier to link other cards:

  • You can now find a button Cite other card above the main text area
  • Clicking this button lets you search for another card
  • Clicking on a search result will paste a Markdown link into the text area

New cards feature: Github-style code blocks

You can now add code blocks without indentation, by using triple-backticks:

```
Code block goes here.
```

Make Capistrano use SSH Key Forwarding

When deploying code with Capistrano (depending on your configuration) at some point Capistrano tries to check out code from your repository. In order to do so, Capistrano connects to your repository server from the application server you're deploying to with SSH. For this connection you can use two SSH keys:

  • the user's ~/.ssh/id_rsa [default]
  • the very same key you used for connecting to the application server - forwarded automatically to the git repository.

If you prefer the second way, add this to deploy.rb:

ssh_options[:forwar...

Git: Retrieve a file from a different branch or commit

To access files from another branch or past commit without doing a complete checkout, you can either use

git show branch:file
git show commit:file

to display, or check out the file into your working directory with

git checkout branch -- file
git checkout commit -- file

Fix ActionController::Session::CookieStore::CookieOverflow

This error simply means you've overloaded a cookie. Hints for fixing:

Check if you're putting too much (e.g. @some_object.inspect) into

  • the session
  • the flash, as it is stored in the session

Use the "retry" keyword to process a piece of Ruby code again.

Imagine you have a piece of code that tries to send a request to a remote server. Now the server is temporarily not available and raises an exception. In order to re-send the request you could use the following snippet:

def remote_request
  begin
    response = RestClient.get my_request_url
  rescue RestClient::ResourceNotFound => error
    @retries ||= 0
    if @retries < @max_retries
      @retries += 1
      retry
    else
      raise error
    end
  end
  response
end

This sni...

Cucumber step to test that a tooltip text exists in the HTML

Tooltips that are delivered through HTML attributes are encoded. Decode entities before checking for their presence.

Capybara:

Then /^there should( not)? be a(n encoded)? tooltip "([^"]*)"$/ do |negate, encoded, tooltip|
  tooltip = HTMLEntities.new.encode(tooltip) if encoded
  Then "I should#{negate} see \"#{tooltip}\" in the HTML"
end

Note

This step uses the htmlentities gem described in another card.

Ma...

Look up a gem's version history

Sometimes it might be helpful to have a version history for a gem, e.g. when you want to see if there is a newer Rails 2 version of your currently used gem.

At first you should search your gem at RubyGems. Example: will_paginate version history.

The "Tags" tab at GitHub might be helpful as well.

Fixing Graticule's "distance" for edge cases

Ever seen this error when using Graticule?

Numerical argument out of domain - acos

Similarly to the to_sql problem for some edge cases, Graticule::Distance::Spherical.distance (and possibly those of Graticule's other distance computation classes) is subject to Float rounding errors.

This can cause the above error, when the arc cosine of something slightly more than 1.0 is to be computed, e.g. for the (zero) distance b...

How to customize CKEditor dialogs

The article gives a very short tutorial how to customize tabs and fields of CKEditor's dialogs.

How to fix a corrupt git index

If your git index for some reason becomes invalid, no need to worry.

Your index is corrupt when you see this error running usual git commands like git pull, git status, etc.:

error: bad index file sha1 signature
fatal: index file corrupt

Though it sounds bad, your changes are still there. Fix it by first removing the index file, then resetting the branch:

rm .git/index
git reset

You should be all good now.

To be safe, make a backup of .git/index before you delete it.

Mac OS X Lion (10.7.2) screws host resolution

As Justin Carmony points out, Mac OS Lion changed its behavior towards DNS and the usage of /etc/hosts (it quite disregards this file).

This has several ugly effects, including:

  • no matter how many Apache Virtual Hosts you've set up, you will only get the first (that is, the implicit default), and only by typing localhost into your browser
  • the Passenger pref pane won't work any more (actually it does, but it has no effect)

turn.js - The page flip effect for HTML5

turn.js is a plugin for jQuery that adds a beautiful transition similar to real pages in a book or magazine for HTML5.

I tested it successfully on Chrome, Firefox and IE9.

nruth/show_me_the_cookies - GitHub

Some helpers for poking around at your Capybara driven browser's cookies in integration tests.

Supports Capybara's bundled drivers (rack-test, Selenium Webdriver), and adapters for other drivers may be added.

Flexible overflow handling with CSS and JavaScript

You can use text-overflow to truncate a text using CSS but it does not fit fancy requirements.

Here is a hack for the special case where you want to truncate one of two strings in one line that can both vary in length, while fully keeping one of them. See this example screenshot where we never want to show an ellipsis for the distance:

![Flexible overflow with optional ellipsis](https://makandracards.com/makandra/5885-a-flexible-overflow-ellipsis/at...

Use CSS "text-overflow" to truncate long texts

When using Rails to truncate strings, you may end up with strings that are still too long for their container or are not as long as they could be. You can get a prettier result using stylesheets.

The CSS property text-overflow: ellipsis has been around for quite a long time now but since Firefox did not support it for ages, you did not use it. Since Firefox 7 you can!

Note that this only works for single-line texts. If you want to truncate tests across multiple lines, use a JavaScript solution like...

Mysql::Error: SAVEPOINT active_record_1 does not exist: ROLLBACK TO SAVEPOINT active_record_1 (ActiveRecord::StatementInvalid)

Possible Reason 1: parallel_tests - running more processes than features

If you run old versions of parallel_tests with more processes than you have Cucumber features, you will get errors like this in unexpected places:

This is a bug caused by multiple processes running the same features on the same database.

The bug is fixed in versions 0.6.18+.

Possib...

Using Vim to repair files with incorrect character encoding/representation

Consider you have a file that uses improper encoding on special characters. Example: You see the latin1 version "ñ" for the UTF-8 "ñ" but the file itself is stored as UTF-8 (meaning that the UTF-8 bytes are doubly encoded).

You can fix that easily with Vim:

vim broken.file

Now you tell vim that the file's encoding is actually latin1 (you can see what Vim is currently using by saying only :set fileencoding):

:set fileencoding=latin1

Write and reload the file:

:w
:e

All should be good now.

Adjust to your n...

Desktop Notifications with WebKit

Chrome now supports desktop notifications using WebKit's webkitNotifications API. This means you can create popup bubbles from Javascript.

Test whether a form field exists with Cucumber and Capybara

The step definition below lets you say:

 Then I should see a field "Password"
 But I should not see a field "Role"

Here is the step definition:

Then /^I should( not)? see a field "([^"]*)"$/ do |negate, name|
  expectation = negate ? :should_not : :should
  begin
    field = find_field(name)
  rescue Capybara::ElementNotFound
    # In Capybara 0.4+ #find_field raises an error instead of returning nil
  end
  field.send(expectation, be_present)
end

Note that you might have to adapt the step defi...

Ubuntu: Reload Gnome panel while keeping user session

Sometimes you need to restart the Gnome panel, e.g. when you installed a new Gnome panel widget but the widget list was cached before.

You often don't want to do sign out and back in for this.
Instead, just run:

killall gnome-panel

This will terminate all gnome-panel processes. On my machine (Ubuntu 11.04) the panel then restarted itself after a moment.

If the panel does not automatically come back, press Alt+F2 to bring up the Gnome "run" box and start gnome-panel from there.

paul/progress_bar - GitHub

ProgressBar is a simple Ruby library for displaying progress of long-running tasks on the console. It is intended to be as simple to use as possible.

Sunspot for Solr fails with '400 Bad Request' in 'adapt_response'

If Sunspot does not work and fails with a backtrace similar to this:

/project/shared/bundle/ruby/1.8/gems/rsolr-1.0.6/lib/rsolr/client.rb:227:in `adapt_response'
/project/shared/bundle/ruby/1.8/gems/rsolr-1.0.6/lib/rsolr/client.rb:164:in `execute'
/project/shared/bundle/ruby/1.8/gems/rsolr-1.0.6/lib/rsolr/client.rb:158:in `send_and_receive'
(eval):2:in `post'

then the schema.xml that is shipped with Sunspot is not loaded into Solr correctly.

Often the latter can be found in /etc/solr/conf/schema.xml. So copy Sunspo...