How to fix: Session hash does not get updated when using "merge!"

tl;dr: Do not use merge! for session hashes. Use update instead.

Outline

Let's assume you're modifying the Rails session. For simplicity, let's also assume your session is empty when you start (same effect when there is data):

# In our example, we're in a Rack middleware
request = Rack::Request.new(env)
request.session.merge! :hello => 'Universe'
request.session
=> {}

Wat?

Even worse: When you inspect your request.session like above (e.g. in a debugger shell, o...

Bootstrap 4 skin for the Rome datepicker

Here is how to make Rome datepicker look like the rest of your Bootstrap 4 application.

Rome comes with very little basic styling. While we could redefine its classes, we can configure the classes Rome applies to its elements to make it look like this:

Example Image

Since Bootstrap 4 comes with several helpful utility classes, and requires fewer markup/containers, we can achieve Bootstrap 4 experience by applying a few classes via the styles setting.

You still need to include `ro...

Upgrade guide for moving a Rails app from Webpack 3 to Webpack 4

Webpacker is Rails' way of integrating Webpack, and version 4 has been released just a few days ago, allowing us to use Webpack 4.

I successfully upgraded an existing real-world Webpack 3 application. Below are notes on everything that I encountered.
Note that we prefer not using the Rails asset pipeline at all and serving all assets through Webpack for the sake of consistency.

Preparations

  • Remove version locks in Gemfile for webpacker
  • Remove version locks in package.json for webpack and webpack-dev-server
  • Install by ca...

Rails: How to get URL params without routing parameters (or vice versa)

Rails' params hash contains any request parameters (URL parameters or request payload) as well as routing parameters like :controller, :action, or :id.

To access only URL parameters, use request.query_parameters. Routing params are available through request.path_parameters.

# On /users?query=Bob&page=2

>> request.params
=> {"page"=>"2", "query"=>"Bob", "controller"=>"users", "action"=>"index"}

>> request.query_parameters
=> {"page"=>"2", "query"=>"Bob"}

>> request.path_parameters
=> {:controller=>"users", :action=>"i...

Micro clearfix mixin for Sass

Clearfix is a hack to clear floating elements without additional HTML markup.

If you only need to support IE8 and above, a great clearfix with few side effects is:

=clearfix
  &:after
    content: ""
    display: block
    clear: both

This is a Sass mixin.

Issues clearing with display: table

You will find many clearfix solutions that clear with display: table instead:

=clearfix
  &:after
    content: ""
    display: table
    clear: both

The problem with th...

Copy to clipboard without flash (clipboard.js)

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js because it does not rely on flash. Flash support of the major browsers has ended.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboar...

JavaScript without jQuery

This is a presentation from 2019-01-21.

Summary

  • We want to move away from jQuery in future projects
  • Motivations are performance, bundle size and general trends for the web platform.
  • The native DOM API is much nicer than it used to be, and we can polyfill the missing pieces
  • Unpoly 0.60.0 works with or without jQuery

Is jQuery slow?

From: Sven
To: unpoly@googlegroups.com
Subject: performance on smartphones and tablets

Hello

I just used your framework in one project and must say,
I am really pleased with it -- but o...

How to install bundler for Ruby < 2.3

Bundler 2 requires at least Ruby 2.3.0 and RubyGems 2.5.0. You might get the following error when you try to install bundler for Ruby < 2.3:

ERROR:  Error installing bundler:
	bundler requires Ruby version >= 2.3.0.

To fix this error upgrade your project's ruby version or install the last supported version of Bundler for Ruby < 2.3:

gem install bundler -v '~>1'

You will also see an error if your [RubyGems versi...

AngularJS 1: How to keep "ng-hidden" elements from flickering on page load

When you have an element you want to hide, you can add a ng-show='isOpen' attribute to that element. When you set isOpen to false on the scope, the element will be hidden.

However, when you load the page, the element is usually rendered by the browser before Angular has loaded and had a chance to hide it.

Generic fix (prefer)

The ng-cloak directive was designed for exactly this purpose. Add a ng-cloak attribute or class (and more, see the link) to any element you want to ...

Carrierwave: Built-in resize methods

Carrierwave includes some handy helper methods you can use to resize your images. Here is a quick summary of them, if you need more details read the docs. You can also use all command line options from RMagick directly if these helpers are not good enough for you.

resize_to_limit(width, height)
resize_to_fit(width, height)
resize_to_fi...

Trigram indexing as an alternative to PostgreSQL fulltext search

For searching in large database tables we usually use PostgreSQL's fulltext search capabilities.

While this works reasonably well for content primarily consisting of prose, it is not necessarily a good solution for all use cases. The main issue is that it is only possible to search for prefixes of text tokens, which can potentially be unexpected for users.

One example are dates:

If you index the text 2019-01-23 15:16, PostgreSQL will create the following tokens: 2019, -01, -23, 15 16. A user searching for 01-23 wi...

How to drop all tables in PostgreSQL

To remove all tables from a database (but keep the database itself), you have two options.

Option 1: Drop the entire schema

You will need to re-create the schema and its permissions. This is usually good enough for development machines only.

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;

Applications usually use the "public" schema. You may encounter other schema names when working with a (legacy) application's database.

Note that f...

RubyGems can't find bundle executable although Bundler is installed

I had this error:

> gem install bundler
Successfully installed bundler-2.0.1
1 gem installed

> bundle install
Traceback (most recent call last):
	2: from /home/henning/.rbenv/versions/2.5.1/bin/bundle:23:in `<main>'
	1: from /home/henning/.rbenv/versions/2.5.1/lib/ruby/2.5.0/rubygems.rb:308:in `activate_bin_path'
/home/henning/.rbenv/versions/2.5.1/lib/ruby/2.5.0/rubygems.rb:289:in `find_spec_for_exe': can't find gem bundler (>= 0.a) with executable bundle (Gem::GemNotFoundException)

The cause was that Bundler 2 requires RubyG...

How to overwrite and reset constants within Cucumber features

In order to save the original value of a constant, set the new value and restore the old value after a scenario was completed, you can use the following helper. It takes care of saving the old constant value, setting the new one without throwing warnings and resets the value with an After hook.

This module also enables you to introduce new global constants.
Since these newly defined constants do not have any value to be reset to,
they simply are deleted (remove_const) once the respective Cucumber step finishes.

You can copy the file at...

Upgrading Ruby from 1.8.7 to 2.3.5

Suggested Workflow

Set the ruby version in .ruby-version to 2.3.5, then perform these steps one by one, fixing errors as they occur:

  1. Update gems as listed below, and bundle
  2. Boot a Rails console - see below for a list of changes you will probably need
  3. Run Specs with --backtrace option
  4. Run Cucumber features (with Geordi's --debug option)
  5. When all tests are green, look through your Gemfile and remove as many version constraints as possible.
  6. Boot the application in different environements to spot further issues, e...

Rails index route for resources named after uncountable substantives

Using uncountable resources is not recommended as it breaks Rails' magic, e.g. when using form_for. You'll always be better off using simple pluralizable resources.


Rails automatically creates path names for routes defined via the resource method. When you put resource 'user' into config/routes.rb, you can call users_path and get the path to the index action in the UsersController: /users.

However, if you have an uncountable resource like Sheep, you cannot access the index action via sheep_path, because it will...

How to create a Basic Auth header value

When doing Basic Authentication, your browser will send an "Authorization" header. Its value is simply a Base64-encoded representation of "username:password" (like when you place credentials in the URL directly). Example for "user@example.com" with password "secret":

Authorization: Basic dXNlckBleGFtcGxlLmNvbTpzZWNyZXQ=

So, in Ruby, you can create such headers like so:

Base64.strict_encode64("#{username}:#{password}")

Note that when speaking to a REST API, you should be using libraries like RestClient or HTTParty which will wrap ...

Ruby: Reading and writing CSVs

In ruby you can easily read and write CSVs with the standard CSV library class.

On top of this, you can use the gem smarter_csv for reading (not writing) CSVs in a more comfortable way:

  • Keep in mind, that the development of this gem is in an unknown state and the 2.0 release seems to happen never
  • The API will change completely for 2.0, so you might find a bunch of unrelated documentation for 1.2

Here is an example...

CSS: How to find out the rendered font in chrome

The rendered font often depends on the local font your system provides, therefore you often find a rule like below in the computed style for an element:

font-family: Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif

This means if your system has a font named Menlo, it will render the text with this font. Otherwise it will try Monaco and so on. For the last two fallback options the system is free to use any monospace font or if not present any serif font. At lea...

Live CSS / view reloading

Next time you have to do more than trivial CSS changes on a project, you probably want to have live CSS reloading, so every time you safe your css, the browser updates automatically. It's pretty easy to set up and will safe you a lot of time in the long run. It will also instantly reload changes to your html views.

Simply follow the instructions below, taken from blog.55minutes.com.

Install CSS live reload (only once per project)

  1. Add th...

Puma: How to force a single threaded boot in development

Puma allows you to specify the max and min threads. In development this could be useful if you use a debugger, but do not want to overflow the console with other request like from ActionCable. Then just set the max threads to 1 and the other requests have to wait.

WORKER_TIMEOUT=1000 puma -t 0:1 -w 1 -p 3000

Cucumber: How to find unused step definitions

Cucumber has an output format that prints step definitions only. You can use this to find unused ones:

  1. Temporarily add require_relative 'env' to the top of the first file in features/support. --dry-run makes Cucumber skip loading env.rb.
  2. Open a really wide terminal window.
  3. bundle exec cucumber --dry-run --format stepdefs | grep -B1 'NOT MATCHED' --no-group-separator | grep features/step_definitions

This will print all unused step definitions from your project – however, the result will include false positives. Step...

Machinist blueprints: Do not set associations without blocks

TL;DR In blueprints, always wrap associations in blocks.

# Broken
Task.blueprint(:vacation) do
  project Project.make(:vacation)
  hours 8
  accounting_method 'none'
end
# Correct
Task.blueprint(:vacation) do
  project { Project.make(:vacation) }
  hours 8
  accounting_method 'none'
end

Without the block, Project.make will only run once when the blueprint is parsed (usually when RSpec is loaded), which is not what you want.

How to upgrade Rails: Workflow advice

When upgrading Rails versions -- especially major versions -- you will run into a lot of unique issues, depending on the exact version, and depending on your app.

However, it is still possible to give some generic advice on how you want to tackle the update in principle.

If you are not really confident about upgrading Rails, have a look at Rails LTS.

How many update steps?

Besides the Rails upgrade itself, you might also want to upgrade your other gems and upgrade your Ruby version.
First decide in how many st...