Chrome DevTools: Treasure (Overview)

tl;dr

The Chrome DevTools are a neat collection of tools for the daily work as a web developer. If you're lucky, you'll maybe find some handy stuff in here.

Analysing

Breakpoints

  • [Breakpoints on HTML Elements](https://makandracards.com/makandra/517982-chrome-devtools...

Sass: get rid of deprecation warnings in dependencies

TLDR: sass >= 1.35.0 has the option quietDeps to silence deprecation warnings from dependencies.

quietDeps: If true, the compiler must not print deprecation warnings
for stylesheets that are transitively loaded through an import path or importer.


You might have seen deprecation warnings like this during assets compilation:

DEPRECATION WARNING: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.
Recommendation: math.div($grid-gutter-width, 2)
More info and automated migrator: https://sass-la...

GitLab: Git alias for creating a merge request on push

Git allows you to set push options when pushing a branch to the remote.
You can use this to build an alias that automatically pushes a branch and creates a merge request for it.

Put this in your ~/.gitconfig in the [alias] section:

mr = push origin HEAD -o merge_request.create -o merge_request.draft

Now you can do git mr and a draft merge request will be created.
Target branch is your project's default branch, i.e. main or master.

To specify a different target branch, add -o merge_request.target=other-branch.

[There...

Debug flaky tests with an Unpoly observeDelay

The problem

Unpoly's [up-observe], [up-autosubmit] and [up-validate] as well as their programmatic variants up.observe() and up.autosubmit() are a nightmare for integration tests.

Tests are usually much faster than the configured up.form.config.observeDelay. Therefore, it may happen that you already entered something into the next field before unpoly updates that field with a server response, discarding your changes.

The steps I wait for active ajax requests to complete (if configured) and capybara-lockstep can catch some ...

Git: Restore

tl;dr

git checkout is the swiss army of git commands. If you prefer a semantically more meaningful command for restoring tasks, use git restore instead.

With this command you can ...

  • ... do unstaging - git restore --staged
  • ... discard staged changes - git restore --staged --worktree
  • ... discard unstaged changes - git restore
  • ... restore deleted files - git restore
  • ... restore historic versions - git restore --source
  • ... recreate merge conflicts - git restore --merge
  • ... specifiy...

How to fix "Exit with code 1 due to network error: ProtocolUnknownError" with wkhtmltopdf

New versions of wkhtmltopdf dissallow file:// URLs by default. You can allow them by passing --enable-local-file-access.

If you are using PDFKit, set the option

PDFKit.configure do |config|
  config.default_options = {
    enable_local_file_access: true,
  }
end

This will be necessary in many setups to allow wkhtmltopdf to fetch assets (such as stylesheets) from the filesystem.

Note on security

Allowing this poses some risk when you render user input, since it might be feasible to include data from the local filesyste...

Git commands to discard local changes

Use case

You have uncommited changes (you can always check by using git status), which you want to discard.

Context

Now there are several options to discard these depending on your exact situation.
The headlines will differentiate the cases whether the files are staged or unstaged.

  1. Staged and unstaged changes
  2. [Staged changes](https://makandracards.com/makandra/516559-git-commands-to-discard-local-changes#s...

RubyMine: Find and Replace with Regex (Capture Groups and Backreferences)

tl;dr

In RubyMine you can use find and replace with capture groups (.*?) and backreferences $1 (if you have several groups: $[Capture-Group ID]).
Named captures (?<text>.*) are also supported.

Examples

Replace double quotes with single quotes

If you want to replace double quotes with single quotes, replacing every " with a ' is prone to errors. Regular expressions can help you out here.

  1. Open find and replace
  2. Activate the regex mode (click on the .* icon next to the "find" field).
  3. Fill in f...

Prefer using Dir.mktmpdir when dealing with temporary directories in Ruby

Ruby's standard library includes a class for creating temporary directories. Similar to Tempfile it creates a unique directory name.

Note:

  • You need to use a block or take care of the cleanup manually
  • You can create a prefix and suffix e.g. Dir.mktmpdir(['foo', 'bar']) => /tmp/foo20220912-14561-3g93n1bar
  • You can choose a different base directory than Dir.tmpdir e.g. `Dir.mktmpdir('foo', Rails.root.join('tmp')) => /home/user/rails_example/tmp/foo20220912-14...

Ruby and Rails: Debugging a Memory Leak

A memory leak is an unintentional, uncontrolled, and unending increase in memory usage. No matter how small, eventually, a leak will cause your process to run out of memory and crash.

If you have learned about a memory leak, looking at the number of Ruby objects by type can help you track it down:

> pp ObjectSpace.count_objects
{:TOTAL=>77855,
 :FREE=>4526,
 :T_OBJECT=>373,
 :T_CLASS=>708,
 :T_MODULE=>44,
 :T_FLOAT=>4,
 :T_STRING=>65685,
 :T_REGEXP=>137,
 :T_ARRAY=>984,
 :T_HASH=>87,
 :T_STRUCT=>12,
 :T_BIGNUM=>2,
 :T_FILE=>3,
 :T_D...

JSON APIs: Default design for common features

When you build a JSON API you need to come up with a style to represent attributes, pagination, errors or including associated objects. Instead of reinventing the wheel, you may reuse successful API designs.

JSON API

JSON:API specifies common features found in most JSON APIs, like pagination, ordering and nested resources. The spec looks very similar to how one would build an API with Rails and uses similar patterns. Even if you don't plan on supporting the whole spec, it can still make sense to know how th...

Converting SVG to other vector formats without Inkscape

If you need to convert an SVG source to PS or EPS, the most common suggestion on the interwebs is to use Inkscape from the commandline.
Inkscape is a fairly resource-heavy tool with lots of dependencies. A great alternative for converting is CairoSVG.

CairoSVG is available on most Linux distros through their package management systems, e.g. apt install cairosvg on Ubuntu.
It has few dependencies (most importantly Python 3 and some related packages, but really not much)...

Web development: Accepting a self-signed certificate in Google Chrome

Working with a self-signed certificate is much easier, when the browser accepts it.

Google Chrome

Warnings from chrome might not be accurate

Even though the certificate is working locally, chrome might still complain that the certificate is not valid and the connection is not secure while blotting out the "https" part of the url.

Accept a specific certificate

  • Go to chrome://settings/certificates
  • Under "Authorities", click "Import"
  • Select the certificate file (.crt)
  • Check "Trust this certificate for identi...

Git: removing feature branches on merge

When working with feature branches, stale branches pile up over time. It's best to remove them right after merge, locally and on the remote, but it is a little tedious: you need to remember it, and perform the few steps manually each time.

Enter Git hooks. The folks at Liquid Light have built a little post-merge hook that will delete a feature branch on confirmation....

Generating and streaming ZIP archives on the fly

When your Rails application offers downloading a bunch of files as ZIP archive, you basically have two options:

  1. Write a ZIP file to disk and send it as a download to the user.
  2. Generate a ZIP archive on the fly while streaming it in chunks to the user.

This card is about option 2, and it is actually fairly easy to set up.

We are using this to generate ZIP archives with lots of files (500k+) on the fly, and it works like a charm.

Why stream downloads?

Offering downloads of large archives can be cumbersome:

  • It takes time to b...

Rails: Fixing the memory leak / performance issues in prepend_view_path

Recently we detected a memory leak in one of our applications. Hunting it down, we found that the memory leak was located in Rails' #prepend_view_path. It occurs when the instance method prepend_view_path is called in each request, which is a common thing in a multi-tenant application.

On top of leaking memory, it also causes a performance hit, since templates rendered using the prepended view path will not be cached and compiled anew on each request.

This is not a new memory leak. It was [first reported in in 2014](https://github.com/...

Reading the Rails session hash from a Rack middleware

To read the Rails session from a Rack middleware, use env['rack.session']. It's an ActionDispatch::Request::Session object.

class MyMiddlware

  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)
    session = env['rack.session']
    Rails.logger.info("Value of session['foo'] is: " + session['foo'].inspect)
    [status, headers, body]
  end

end

You may not be able to write to the session this way (I haven't tested this).

Fix: esbuild assets are missing after capistrano deploy

Issue: You have an app using jsbundling-rails and esbuild. After deploy, the assets built by esbuild are missing in public/assets.

Solution: Add app/builds to your git repo (by adding a app/builds/.keep file).

Something in sprockets is caching paths and refuses to accept files in "unknown" locations.

JavaScript: Testing whether the browser is online or offline

You can use the code below to check whether the browser can make connections to the current site:

await isOnline() // resolves to true or false

Limitations of navigator.onLine

While you can use the built-in function navigator.onLine (sic), it is only a hint for whether the device can access the Internet.

When navigator.onLine === false you know for certain that the user device has no connection to the Internet. This mea...

Rails: Default HTTP status codes when redirecting

When redirecting you should take care to use the right HTTP status code.

From controllers

When redirecting from a controller, the default status code is 302 Found (aka Moved Temporarily):

red...

Show a JS fiddle in fullscreen

If you have a JS fiddle, you can open it in fullscreen by appending /show to the URL.

Example: https://jsfiddle.net/b275g910/3 => https://jsfiddle.net/b275g910/3/show

Capybara: Most okayest helper to download and inspect files

Testing file download links in an end-to-end test can be painful, especially with Selenium.

The attached download_helpers.rb provides a download_link method for your Capybara tests. It returns a hash describing the download's response:

details = download_link('Download report')
details[:disposition]  # => 'attachment' or 'inline'
details[:filename]     # => 'report.txt'
details[:text]         # => file content as string
details[:content_type] # => 'text/plain'

Features

Compared to [other approaches](...

Getting different results working with SVG files and ImageMagick

When you are working with SVG files and ImageMagick you can get different results on different machines depending on which additional packages you have installed.

From: http://www.imagemagick.org/script/formats.php

ImageMagick utilizes inkscape if its in your execution path otherwise RSVG. If neither are available, ImageMagick reverts to its internal SVG renderer.