3488 cards

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…


Traverse an ActiveRecord relation along an association

The Edge Rider gem gives your relations a method #traverse_association which
returns a new relation by "pivoting" around a named association.

Say we have a Post model and each Post belongs to an author:

class Post < ActiveRecord::Base
  belongs_to :author

To turn a relation of posts into a relation of its authors:

posts = Post.where(:archived => false)
authors = posts.traverse_association(:author)

You can traverse multiple associations in a single call.
E.g. t…

How to add a user with all privileges to MariaDB

Add a user with password

mysql -uroot -p
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'changeme';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

Add a user without password

mysql -uroot -p
CREATE USER 'newuser'@'localhost' IDENTIFIED BY '';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

If you don't have a user with the sufficient access rights, follow these steps to reset…


Operators "in" and "of" are very inconsistent between CoffeeScript and JavaScript

CoffeeScript and JavaScript (ECMAScript) both have operators in and of. Each language use them for more than one purpose. There is not a single case where the same operator can be used for the same purpose in both languages.

Check if an object (or its prototype) has a property


var hasFoo = 'foo' of object


var hasFoo = 'foo' in object;

Iterate through all properties of an object


Don't build randomness into your factories

Tests are about 100% control over UI interaction and your test scenario. Randomness makes writing tests hard. You will also push tests that are green for you today, but red for a colleague tomorrow.

That said, please don't do something like this:

Factory(:document) do |document|
  document.category { ['foo', 'bar', 'baz'].sample }

Instead do this:

Factory(:document) do |document|
  document.category 'foo'

The case against Faker

I even recommend to not use libraries like [Faker](http://…

How to make Capistrano not truncate server output

By default, Capistrano truncates server responses and places an ellipsis at the end of lines that are longer than your terminal. Error messages are never truncated.

While this can be helpful to make deployment output appear less noisy, it also hides information that could be helpful.
I believe you should prefer knowing what is going on, even if causes a few extra lines of output.

Capistrano by default uses Airbrussh which is where truncation happens. To disable truncation globally, place this into your deploy.rb:

set :format_options...

CSS: Using the current text color for other color properties

There is a kinda secret, yet well supported CSS feature called currentColor. It's like a special CSS variable that has been supported in almost all browsers for almost all time (see linked Caniuse).


The currentColor value can be used in CSS to indicate the current value of color should be used. A common use case is setting a border color:

  color: white
  border: 1px solid currentColor
    color: red // Border color will change as well 

Note that in many cases, you can simply omit the color to ac…

External contentRepeats


Nested exceptions for Ruby:

When you rescue an error and then re-raise your own, you don't have to lose track of what actually occured, you can keep/nest the old error in your own and the stacktrace will reflect the cause of the original error.

This is awesome when you classes convert exception classes. I now always subclass Nesty::NestedStandardError instead of StandardError for my own error classes.

About Exception#cause

Ruby 2.1 has a built-in mechanism with Exception#cause, which serves a similiar purpos…


Jasmine: Adding custom matchers


A matcher is a function that returns an object with a compare key. Usually it is registered with beforeEach:

beforeEach ->
    # Example matcher
    toBeAnything: ->
      compare: (actualValue, matcherArguments...) ->
         # Do some computations here ...
         # Return whether the actualValue matches the expectation
         pass: true



When a matcher is invoked, Jasmine will call its compare() fu…


Rails route namespacing (in different flavors)

TL;DR There are three dimensions you can control when scoping routes:

scope module: 'module', path: 'path', as: 'as' do
  resources :examples, only: :index

=> Path Helpers: as_examples_path and as_examples_url
=> URLs: /path/examples
=> Controller module: Module::ExamplesController and views location: app/views/module/examples/

Changing URLs only

When you want to namespace some paths but leave the corresponding controllers and url helpers unaffected, you can use the scope method like follows:

scope path…

External content

screenfull.js: Simple wrapper for cross-browser usage of the JavaScript Fullscreen API

Using the JS fullscreen API is painful because all browers use different methods and events and you need to use lots of boilerplate code to make your application work in all browsers.

The "screenfull" library wraps that for you, including events.


The linked GitHub repo contains some information. You basically use the library like this:

// Make an element go fullscreen

// Leave fullscreen

Unpoly: Loading large libraries on-demand

When your JavaScript bundle is so massive that you cannot load it all up front, I would recommend to load large libraries from the compilers that need it.

Compilers are also a good place to track whether the library has been loaded before. Note that including same <script> tag more than once will cause the browser to fetch and execute the script more than once. This can lead to memory leaks or cause duplicate event handlers being registered.

In our work we mostly load all JavaScript up front, since our bundles are small enough. We recent…


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…

How to fix: Rbenv fails to install Ruby 1.8.7 with OpenSSL

Installing ruby 1.8.7 with rbenv might fail if you have installed libssl-dev instead of libssl1.0-dev (default in Ubuntu 18.04).

Run sudo apt install libssl1.0-dev to remove libssl-dev and add libssl1.0-dev.

You can check installed libssl packages using apt list:

$ apt list –installed | grep libssl

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

libssl-dev/bionic,now 1.1.0g-2ubuntu4 amd64 [installed]
libssl-doc/bionic,bionic,now 1.1.0g-2ubuntu4 all [installed,automatic]


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 corporate website to learn more about the corporation.'


= t('.text')

Desired output

Please visit our <a href="https://w…


RubyMine: Scratch files

There are times when you have a chunk of text that you want to do something with, e.g. replace something on it, or quickly edit it.

While you can open your favorite non-RubyMine editor for this, there is also a plugin: Scratch.

It allows RubyMine to open temporary files (actually they are saved, but somewhere inside the plugin's directory) so you don't need to switch to a text editor like gEdit that works differently and may not even offer what you are used to.

Note that RubyMine also offers so…

Capistrano task to tail remote application logs of multiple servers

When your application is running on a multi-server setup, application logs are stored per server (unless you choose a centralized logging solution).
Here is a Capistrano task that connects to all servers and prints logs to your terminal like this:

$ cap production app:logs
00:00 app:logs
      01 tail -n0 -F /var/www/your-application/shared/log/production.log | while read line; do echo "$(hostname): $line"; done
      01 app01-prod: Started GET "/sign_in" for at 2018-04-26 11:28:19 +0200
      01 app01-prod: Proc...

jQuery: How to replace DOM nodes with their contents

You know that you can use jQuery's text() to get an element's contents without any tags.
If you want to remove only some tags, but keep others, use contents() and unwrap(). Here is how.

Consider the following example element.

$container = $('<div><strong>Hello</strong> <em>World</em></div>')

Let's say we want to discard any <em> tags, but keep their contents.
Simply find them, then dive into their child nodes via contents, and use unwrap replace their …

This website uses cookies to improve usability and analyze traffic.
Accept or learn more