Speed up response time in development after a Sass change

When working with large Sass files you will notice that the first request after a change to a Sass file takes quite some time. This is because the CSS files are being generated from the Sass files the moment the application answers your request (Sass looks at the files and recompiles if the timestamp changed); it takes even longer when you build sprites with the Lemonade gem.

To avoid this, have Sass watch the files for changes and compile them into CSS files immediately. Th...

Delete all MySQL records while keeping the database schema

You will occasionally need to clean out your database while keeping the schema intact, e.g. when someone inserted data in a migration or when you had to kill -9 a frozen test process.

Old Capybara versions already have the Database Cleaner gem as dependency. Otherwise add database_cleaner to your *Gemfile`. This lets you say this from the Rails console:

DatabaseCleaner.strategy = :truncation
DatabaseCleaner.cl...

Synchronize a Selenium-controlled browser with Capybara

When you click a link or a press a button on a Selenium-controlled browser, the call will return control to your test before the next page is loaded. This can lead to concurrency issues when a Cucumber step involves a Selenium action and a Ruby call which both change the same resources.

Take the following step which signs in a user through the browser UI and then sets a flag on the user that was just signed in:

Given /^the user "([^"]*)" signed in (\d) days ago$/ do |name, days|
  visit new_session_path
  fill_in 'Username', :w...

Monitoring Theory

Around the time in my life when I stopped ordering drinks made with more than one ingredient, I was woken up for the last time by a hypochondriac Nagios monitoring installation. If you are on-call long enough, you cultivate a violent reaction to the sound of your cell phone's text message alert. If your monitoring is overconfigured, that reaction boils over hastily, as it will interrupt you during meals, sex, sleep — all of the basics — with the excruciating operational details of your web site.

I've since developed, with the help of some n...

plus2/whereuat - GitHub

Adds a slide out panel to your Rails application that directs clients to test stories that have been marked as 'delivered' in Pivotal Tracker.

Prevent floating sibling elements from wrapping in CSS

When you style multiple adjacent block elements with float: left, they will be rendered next to each other similar to inline elements. Also like inline elements, they will wrap at the horizontal end of the parent container.

If you want to keep floating elements from wrapping, nest them in a really wide container:

<div class="tabs">
  <div class="really_wide_container">
    <div class="tab">...</div>
    <div class="tab">...</div>
    <div class="tab">...</div>
  </div>
</div>

This is the [Sass](http://sass-la...

Unexpected behavior when changing both an association and its foreign key attribute in ActiveRecord

When you set both a record's association and that association's foreign key attribute, Rails does not realize you are talking about the same thing. The association change will win in the next save, even if the foreign key attribute was changed after the association.

As an example, assume you have these two models:

class Group < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  validates_presence_of :group_id
  belongs_to :group
end

We will now load a User and change both its `g...

Remove quotes from Sass mixin arguments

When calling a Sass mixins, you usually don't need to quote arguments:

+tint_article(#f21)

However, when a CSS property consists of multiple parts (like background or box-shadow), the Sass parser will trip up:

+box_shadow(0 1px 2px #000) // this will blow up

The solution is to quote the argument like this:

+box_shadow('0 1px 2px #000')

As the author of the box-shadow mixin you now need to unquote this string, so the quotes don't appear in the resulting CSS. E.g. the following version of the box-shadow mixin will...

Check that a Range covers an element in both Ruby 1.9 and 1.8.7

In order to cover some edge cases you rarely care about, Range#include? will become very slow in Ruby 1.9:

Range#include? behaviour has changed in ruby 1.9 for non-numeric ranges. Rather than a greater-than/less-than check against the min and max values, the range is iterated over from min until the test value is found (or max) [...] Ruby 1.9 introduces a new method Range#cover? that implements the old include? behaviour, however this method isn’t available in 1.8.7.

The attached ...

Fix Capistrano with RubyGems 1.6

After updating your RubyGems, you will probably not be able to run Capistrano any more, but receive an error similar to this:
can't activate net-ssh (= 2.0.22) for [], already activated net-ssh-2.1.0 for [] (Gem::LoadError)

If you have Bundler installed, you can use bundle exec to avoid this problem as follows:

Create a gemfile at ~/.capistrano/Gemfile (or at some other sensible place), that only contains these 2 lines:
source 'http://rubygems.org'
gem 'capistrano'
gem 'capistrano-ext' # You need this for multistag...

Keyboard shortcuts for Pivotal Tracker

Pressing the ? key will display a list of keyboard shortcuts. Available shortcuts are:

|search |/|
|help|?|
|add story|a|
|toggle backlog|<Shift> + b|
|toggle charts (graphs)|<Shift> + g|
|toggle current|<Shift> + c|
|toggle done|<Shift> + d|
|toggle history|<Shift> + h|
|toggle icebox|<Shift> + i|
|toggle my work|<Shift> + w|
|toggle labels & searches|<Shift> + l|

This is awesome.

Fixing "uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)"

RubyGems 1.6.0 has undergone some changes which may cause Rails 2.x applications to break with an error like this one (e.g. when running script/server):
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:55: uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

Fix it by adding the following not only to your environment.rb but also into your script/server file, in both cases before boot.rb is required.
require 'thread'

If you still get the error above you can also add `require 'thre...

Convert Adobe Flash FLA files into HTML5 with Wallaby

"Wallaby" is the codename for an experimental technology that converts the artwork and animation contained in Adobe® Flash® Professional (FLA) files into HTML. This allows you to reuse and extend the reach of your content to devices that do not support the Flash runtimes. 

Check whether a getter is an attribute or an association

Sometimes you might want to know if an attribute is an associated object or a simple string, integer etc. You can use the reflect_on_association method for that.

if Person.reflect_on_association(:address)
  Person.address.attributes # do something
else
  Person.address # do something else
end

Closures in Ruby

If you want to get a deep understanding of how closures, blocks, procs & lambdas in Ruby work, check out the code at the attached link.

Here the summary:

^
---------------------------- Section 6: Summary ----------------------------

 So, what's the final verdict on those 7 closure-like entities?          

                                                     "return" returns from closure
                                    True closure?    or declaring context...?         Arity check?
                         ...

Function to return the minimum or maximum value per row with MySQL

MySQL's MIN and MAX functions are for aggregations only. This will not work and produce an error:

SELECT id, MIN(birthday, '1978-01-01') FROM users;

In order to compute the minimum or maximum value for the current row, use LEAST and GREATEST instead:

SELECT id, LEAST(birthday, '1978-01-01') FROM users;

Export more than 500 rows in Google Analytics

Currently, only up to 500 rows of Analytics table data can be exported at a time into CSV format. If you need to export larger data sets, like exporting all keywords that sent traffic to your site, you can export multiple times as long as each batch contains at maximum 500 rows.

If you have thousands of rows that require multiple exports, you can use the convenient workaround below to export all your rows in one go.

Dual monitors crashing Linux with NVIDIA drivers

My T410 has a NVIDIA graphics card (NVS 3100M).

My BIOS configuration looks like this:

  • NVIDIA Optimus is disabled in
  • "Discrete" mode on
  • Internal Intel card deactivated

My X crashed when trying to activate both Dell U2410 monitors connected using DVI to the docking station.

The solution was to disable DDC/CI on the monitors: Menu -> Other settings -> DDC/CI disable

Note that you shouldn't disable DDC/CI if you don't have any issues with your displays.

Add a prefix to form field IDs

If you use a form (or form fields) multiple times inside one view, Rails will generate the same id attributes for fields again.

This card presents you with a way to call something like

- form_for @user, :prefix => 'overlay' do |form|
  = form.text_field :email

and get this as HTML:

<input name="user[email]" id="overlay_user_email" (...) />

You can also put a :prefix into a field's options. Note how only the id but not the name changes as we would not want to pass an overlay_user[email] param to the controller. Sett...

Exchange messages between Javascript and Flash

Flash movies (.swf files) can talk with Javascript code embedded in the same HTML page. There are two ways to do this:

  • The preferred way is to use the ExternalInterface class to call Javascript functions from ActionScript, and to bind ActionScript functions to the Flash movie's DOM element so they can be called from Javascript.
  • The deprecated way is to use the global [fscommand](http://help.adobe....

Insert an ndash and other special characters using the Compose key on Linux

Although you can access many symbols using the AltGr key you may be missing some, like the en-dash (–) or em-dash (—). You can use a compose key for them instead.

First, make sure you have a compose key configured.

Configuring a compose key

I suggest using the "Menu" key which is located between the right Meta and Ctrl key.

Ubuntu / MATE

Control Center → Keyboard → Layout → Options → Position of Compos...

Configuring User Agents with Capybara + Selenium Webdriver

A while ago we were working on an application that had an entire version specially created for mobiles, such as the iPhone. This specific application was entirely tested with Capybara, Steak and Selenium Webdriver. Although the test suite wasn’t the fastest one in the world, the web application was very well tested, and to guarantee that we would also be testing the mobile version, we would have to simulate an iPhone user agent accessing the application.

But wait, you might be thinking that we are not able to change browser headers while ...

Paperclip: Image resize options

Paperclip uses the imagemagick resize options like 100x50> , 100x50<, 100x50# etc to resize images.
See the link what options are available.

  • ('!') Ignore Aspect Ratio
  • ('>') Only Shrink Larger
  • ('<') Only Enlarge Smaller
  • ('^') Fill Given Area
  • ('%') Percentage Resize
  • ('@') Pixel Area Limit
  • ('#') Crop thumbnail centrally and ensure the requested dimensions, not documented at imagemagick doc

Escaping of quotation marks in Cucumber steps and step definitions

Issue

When you have a Cucumber step like

Then I should see "Did you see those \"quotation marks\" over there?"

you'll run into trouble. Cucumber won't take your escaped quotation marks.

Workarounds

One workaround is to write the step as regex (since there is a step taking a regex):

Then I should see /Did you see those "quotation marks" over there\?/

Keep in mind it’s a regex – escape regex characters like '?'.

When you have a Cucumber step like

Then I should fill in "query" with "\"some phrase\""

The fo...