3733 cards

How to reset a Mock

With Rspec you can mock objects or functions, for example like this:

expect(my_object).to receive(:my_function).and_return('hello world')

It's also easy to remove mocks for an object:


whenever: Installing cron jobs only for a given Rails environment or Capistrano stage

We use the whenever gem to automatically update the crontab of the servers we deploy to. By default, whenever will update all servers with a matching role (we use the :cron role ).

This card describes how to install some tasks only for a given Rails environment or for a given Capistrano stage.

Installing jobs only for a given Rails environment

In yo...


How Ruby method lookup works

When you call a method on an object, Ruby looks for the implementation of that method. It looks in the following places and uses the first implementation it finds:

  1. Methods from the object's singleton class (an unnamed class that only exists for that object)
  2. Methods from prepended modules (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its ancestors)


Let's say we h...


Manipulate color with Sass functions

Sass comes with many built-in functions to manipulate color. Some of the more interesting functions include:

adjust-hue($color, $degrees)
Changes the hue of a color.

lighten($color, $amount)
Makes a color lighter.

darken($color, $amount)
Makes a color darker.

saturate($color, $amount)
Makes a color more saturated.

desaturate($color, $amount)
Makes a color less saturated.

Converts a color to grayscale.

Returns the compleme...

Linked contentRepeats

The Self-Contained Test

One of the earliest pieces of wisdom we are given as programmers is to not write duplicate code: Don’t Repeat Yourself (or DRY if you prefer). Identical blocks of code to set up a test sure does look like repetition, so we extract it into a before block.

This is a mistake for tests.

The article explains about how sharing setup between examples make test files harder to read and evolve.

A related frustration I have is working on ultra-DRY & betterspecs-like ...

Rspec: Expecting a Rake task to be called

This seems to be obvious, but you can expect Rake tasks to be called in RSpec.

it 'deletes all Users' do
   expect(Rake::Task['notify:critical_operation']).to receive(:invoke)
   expect { described_class.clean }.to change(User, :count).from(1).to(0) 

Note: Try to avoid logic in rake tasks and prefer to just call classes in them.


desc 'Some task'
task :some_task do
Linked contentRepeats

Rails: Including HTML in your i18n locales

TL;DR Append your locale keys with _html to have them marked as html_safe.

When you're localizing a Rails application, sometimes there is this urge to include a little HTML. Be it some localized link, or a set of <em> tags, you'd like to have it included in the locale file. Example:

# Locale file
    text: 'Please visit our <a href="https://www.corporate.com/en">corporate website</a> to learn more about <em>the corporation</em>.'
= t('.text')
# Desired output
Please visit our <a href="https://w...

BigDecimal arithmetic in Ruby

Ruby comes with a class BigDecimal which you can use for arbitrary precision arithmetic. You should use BigDecimal instead of Float whenever you care about rounding errors, e.g. whenever you are dealing with money.

You should remember these two rules when working with BigDecimal values:

  • When you add or multiply a BigDecimal with another BigDecimal, the ...
Linked contentAuto-destruct in 24 days

Unpoly 0.62.0 released (accessibility improvements)

This release backports a number of accessibility improvements from the next major version of Unpoly.
We encourage everyone to upgrade to this release in order to better support users with visual impairments.

The following changes are included:

  • Links with an [up-instant] attribute can now be followed with the keyboard.
  • Fragments that are being destroyed now get an [[aria-hidden=true]](https://developer.mo...

How to use git fixup

Using git fixup helps you to speed up appending changes further back in the git history of your feature branch.


git commit --fixup aabbcc # Create a commit with the message "fixup! Commit message of aabbcc"
git rebase -i --autosquash master

It would be nice if you could use this feature without the -i flag, but until now it seems not to be possible. Read more about our recommended git workflow for feature branches.

Linked contentAuto-destruct in 16 days

cucumber_factory 2.1.1 released

We released a new version of cucumber_factory, which stabilizes the use of transient record references within your steps.

2.1.1 - 2020-05-20

Compatible changes

  • Cucumber 2.1.0 introduced some regressions which are being addressed with this patch:
    • Fix the assignment of polymorphic associations.
    • Restore the support for inherited traits within nested factories.

2.1.0 - 2020-03-09

Compatible changes

  • Allow associations to be set for [transient attribut...

How to update a single gem conservatively

The problem

Calling bundle update GEMNAME will update a lot more gems than you think. E.g. when you do this:

bundle update cucumber-rails

... you might think this will only update cucumber-rails. But it actually updates cucumber-rails and all of its dependencies. This will explode in your face when one of these dependencies release a new version with breaking API changes. Which is all the time.

In the example above updating cucumber-rails will give you Capybara 2.0 (because capybara is a dependency of `cucumber-rail...

Installing multiple MySQL versions on the same Linux with mysql-sandbox

Ubuntu has a package mysql-sandbox that lets you install multiple MySQL versions into your user home:

  1. Install mysql-sandbox
sudo apt install mysql-sandbox
  1. Download the version of MySQL you want to use from mysql.com:
    Make sure to choose "Generic Linux" instead of "Ubuntu" so you get a .tar.gz instead of .deb

  2. cd into the directory the mysql binaries will be extracted to

mkdir -p ~/bin/sandbox_dist
cd ~/bin/sandbox_dist
  1. Build the sandbox

netstat: How to show listening ports

Sometimes it's necessary for you to check which ports are in use on your local machine and which process is using it. To list this information you can use the following command (which is pretty easy to memorize for Germans 🌷):

sudo netstat -tulpn
  • t: tcp
  • u: udp
  • l: listening ports
  • p: process
  • n: network

Use sudo to see the name of the process.

Finding open ports in the netstat output

You should look for rows with State: LISTEN.

Rows for local address or :...

Linked contentAuto-destruct in 9 days

Updated: How to discard a surrounding Bundler environment

Updated card to use Bundler.with_original_env which is what you actually always wanted.

Also added a note on what with_unbundled_env (or with_clean_env on legacy versions) does.


HTML: Making browsers wrap long words

By default, browsers will not wrap text at syllable boundaries. Text is wrapped at word boundaries only.

This card explains some options to make browsers wrap inside a long word like "Donaudampfschifffahrt".

Option 1: Soft hyphens

Unicode has a soft hyphen character you can use to mark optional word division opportunities. The soft hyphen is an invisible character with zero width. Only when the browser decides to wrap at a soft hyphen, it is turned in...

Linked contentRepeats

Lazy-loading images

Since images are magnitudes larger in file size than text (HTML, CSS, Javascript) is, loading the images of a large web page takes a significant amount of the total load time. When your internet connection is good, this is usually not an issue. However, users with limited bandwidth (i.e. on mobile) need to mine their data budget better.

One popular strategy to improve the website performance is to not load images until they enter the viewport – aka "lazy-loading images".

General Issues

  • Crawlers do not execute JavaScript (generally sp...

Rails: When defining scopes with class methods, don't use `self`

Sometimes it is useful to define a named scope by implementing a static method with the scope's name on the scoped class. For instance, when a method should decide which existing scope should be the next link in the scope chain. Take this class for example:

class Meal < ActiveRecord::Base

  named_scope :for_date, lambda { |date| :conditions => { :date => date }}
  named_scope :with_meat, :conditions => { :meat => true }
  named_scope :without_meat, :conditions => { :meat => false }

  def self.suitable_for(user)
This website uses cookies to improve usability and analyze traffic.
Accept or learn more