Better performance insights with gem `rails_performance`
Even if you don't make any beginner mistakes like N+1 queries or missing DB indices, some requests can have bad performance. Without good performance metrics, you probably won't notice this until it's too late.
We investigated multiple gems and found that rails_performance
(https://github.com/igorkasyanchuk/rails_performance) provides a lot of valuable information with very little setup cost. It only needs Redis which we use in the majority of our applications anyw...
Selenium: Fix Chrome's "Unsafe Password" Warning
tl;dr
Set
profile.password_manager_leak_detection
tofalse
in your Selenium Chrome options to disable password leak detection and suppress the warning.
Problem
When running Selenium tests with recent versions of Chrome and Chromedriver (e.g., version 136+), entering “unsafe” (weak or reused) passwords in forms triggers a browser warning:
"This password has appeared in a data breach…"
This alert can break automated test runs, especially in CI/CD pipelines.
Solution
You can **disable Chrome’s password leak ...
Output of ParallelTests::Cucumber::FailuresLogger was fixed in 4.9.1
Our projects with parallel_tests
and cucumber
used to have a patched failure logger as the one from parallel_tests
was missing spaces which resulted in the output not being a valid rerun argument. With version 4.9.1
output of ParallelTests::Cucumber::FailuresLogger
was fixed.
You can remove the patch (e.g. features/support/cucumber_failures_logger.rb
) and switch the logger in config/cucumber.yml
back to ParallelTests::Cucumber::FailuresLogger
.
Thanks to Dominik for [the fix](https://github.com/grosser/parallel_tests/commit/...
Selecting the nth element matching a selector
The :nth-child
pseudo class is commonly used for targeting elements based on their position within a parent container, for example the third element in a list or every even-numbered item. However, :nth-child
can do more.
In modern CSS specifications (Level 4), there’s an additional feature that lets you use :nth-child
in combination with a list of css selectors. This way, you can ta...
Git Rebase: How to squash/fixup/edit/... commits without actually rebasing (keeping the base)
Purpose:
Interactively rebase your current branch onto main
, keeping the original base commit (i.e. not rebasing onto main
directly).
Use Case:
Useful when you've branched off a long-lived feature branch and want to clean up your commits without changing the original base. Afterwards you will be able to rebase one clean commit interactively onto main without going through each commit individually using git rebase -i main
.
What it does:
- Opens an interactive rebase UI to choose squash/edit/fixup for each co...
How to set Chrome's time zone in Selenium tests
For Selenium tests, your browser starts in your local timezone, or whatever your system's environment specifies.
This is usually good enough. To test any timezone-dependent behavior in Chrome, you can change the time zone using the Chrome DevTools Protocol.
Example
Chrome accepts any IANA time zone name, like "Europe/Berlin" or "Asia/Tokyo".
Here is the relevant command for Capybara:
page.driver.browser.execute_cdp('Emulation.setTimezoneOverride', timezoneId: 'Asia/Tokyo')
``...
Rails: Keeping structure.sql stable between developers
Why Rails has multiple schema formats
When you run migrations, Rails will write your current database schema into db/schema.rb
. This file allows to reset the database schema without running migrations, by running rails db:schema:load
.
The schema.rb
DSL can serialize most common schema properties like tables, columns or indexes. It cannot serialize more advanced database features, like views, procedures, triggers or custom ditionaries. In these cases you must switch to a SQL based schema format:
# in application.rb
config.a...
A "text-wrap: balance" fallback approach
Here is a workaround for when you want to use text-wrap: balance but must also render nicely for browsers that don't support it (mostly Safari <17.5).
Step 1: Put some <br>
s into your HTML
First, place explicit line breaks that should work for most cases.
This depends on your use case and is affected by e.g. container widths or user content.
<div class="my-element">
<p>
Average score
<br>
...
How to automatically optimize SVG files with esbuild
SVG files often contain redundant information, like editor metadata or hidden elements. When esbuild handles your static assets, you can easily optimize SVG files using svgo as a plugin. Here is how to do it.
Adding svgo as an esbuild plugin
- Add the
svgo
package to your project'spackage.json
- Adjust your
esbuild.config.js
like so:
const esbuild = require('esbuild')
const svgo = require('svgo')
const options = {
// ...
loader: {
// ...
'.svg': 'copy', // this may be different...
Rails: Using PostgreSQL full-text search without a gem
PostgreSQL can cosplay as a full-text search engine. It doesn't have the features or fidelity of ElasticSearch or Algolia, but it's good enough if you just need to search and rank large volumes of text.
This card will teach you how to index, search and rank your Rails models in a PostgreSQL full-text index. We will do this without using any gems aside from ActiveRecord. While there are gems like pg_search or pg_fulltext, manual integration requires very...
Using Low-Level Prompts for High-Accuracy AI Coding
The key to unlocking the full potential of LLMs in coding lies in crafting precise prompts. The main challenge is learning how to structure prompts effectively to guide the model toward accurate results. Further evidence supporting this is the fact that Aider already writes ~70% of its own code (as of 02/2025). However, when starting out, your results may fall short of efficiently generating large portions of your code with the...
How to disable telemetry for various open source tools and libraries
Hint
If you are using our opscomplete.com hosting we can set all environment variables mentioned below for your deployment on request.
If you're lucky DO_NOT_TRACK=1
opts you out of CLI telemetry - it's not widely adopted. When you're using any of the libraries below, I'd rather opt out explicitly:
Yarn
https://yarnpkg.com/advanced/telemetry (Since: Version 2.2)
Disable for a project:
#...
Ignore Selenium driver deprecations
If you update Selenium regularly, you'll run into deprecation warnings similar to:
WARN Selenium [:clear_local_storage] [DEPRECATION] clear_local_storage is deprecated and will be removed in a future release
You can ignore this deprecation warning and clean your logs with logfilters:
Selenium::WebDriver.logger.ignore(:clear_local_storage)
Just specify the tag (:clear_local_storage
) you want to ignore.
How the Date Header Affects Cookie Expiration and Caching
tl;dr
When a cookie includes an
Expires
attribute or an HTTP response includes caching headers likeExpires
orCache-Control
, their validity depends on the server'sDate
header if present. Otherwise, the browser uses its local time. This can lead to issues in tests with mocked time or inconsistent cache behavior.
Cookie Expires
depends on the Date
header or browser time
When a cookie includes an Expires
attribute, the browser evaluates the expiration date relative to a reference time:
- If the HTTP response ...
Text fragments in the browser URI fragment
Text fragments allow linking directly to a specific portion of text in a web document, without requiring the author to annotate it with an ID, using particular syntax in the URL fragment. Supporting browsers are free to choose how to draw attention to the linked text, e.g. with a color highlight and/or scrolling to the content on the page. This is useful because it allows web content authors to deep-link to other content they don't control, without relying on the presence of IDs to make that possible. Building on top of that, it could be u...
Enabling YJIT
YJIT is Ruby's default just-in-time compiler. It is considered production-ready since Ruby 3.2 (source).
To activate YJIT you need two steps:
- Your
ruby
binary needs to be compiled with YJIT support. - You need to enable YJIT.
Getting a Ruby with YJIT support
We usually install Ruby with tools like rbenv
or asdf
. This compiles the ruby
binary from the source code. Support for YJIT
will be automatically added during this compilation...
DB enums are ordered
A lesser known fact about PG enums is that they are ordered. This can be really handy when values have an implicit ordering.
Let's imagine a record Issue(criticality: string)
. criticality
should have the following three possible values: critical
, medium
, low
.
Sorting with Issue.all.order(criticality: :desc)
will return the following order:
- The
'medium'
issue - The
'low'
issue - The
'critical'
issue
This happens because the database column backing the criticality attribute is a string and PG will use a [collation](...
Switching the package manager from yarn to npm
We recently migrated a Rails application from yarn
to npm
. We decided to go this step instead of upgrading to > Yarn 2.0 to reduce the number of dependencies in our project.
Migration
- Remove the
yarn.lock
file - Remove the
node_modules
folder - Run
npm install
- Replace all occurrences of
yarn
withnpm
in your project
Notes
- With
npm
vendored packages with dependencies create their ownnode_modules
folder within the vendor path. We...
Running Cucumber deletes my whole app!
If a Cucumber run deletes your application directory, an integration fail between Capybara and Capybara Screenshot may be the cause. Capybara Screenshot defaults to storing screenshots in .
, and tidying up screenshots happens to "tidy up" the application as well. Seen with Capybara 2.18 and Capybara Screenshot 1.0.4.
Upgrading Capybara Screenshot to 1.0.26 fixes the issue. Consider also setting Capybara.save_path = 'tmp/capybara'
in an initializer.
Learn how to use ruby/debug
This talk shows simple and advanced usages of the ruby/debug debugger. It goes through a step by step debugging workflow.
Here are some command examples:
(rdbg) step 2 # step twice
(rdbg) info # show current scope, including self
(rdbg) bt # show backtrace
(rdbg) frame 3 # go directly to frame 3
(rdbg) break User#email # add a breakpoint in the email instance method
(rdbg) catch SomeException # break when SomeException is raised
Some advanced exam...
How to allow testing beforeunload confirmation dialogs with modern ChromeDrivers
Starting with ChromeDriver 127, if your application displays a beforeunload
confirmation dialog, ChromeDriver will immediately close it. In consequence, any automated tests which try to interact with unload prompts will fail.
This is because ChromeDriver now follows the W3C WebDriver spec which states that any unload prompts should be closed automatically.
However, this applies only to "HTTP" test sessions, i.e. what you're using by default. The spec also defines that bi-directional test se...
High-level data types with "composed_of"
I recently stumbled upon the Rails feature composed_of. One of our applications dealt with a lot of addresses and they were implemented as 7 separate columns in the DB and Rails models. This seemed like a perfect use case to try out this feature.
TLDR
The feature is still a VERY leaky abstraction. I ran into a lot of ugly edge cases.
It also doesn't solve the question of UI. We like to use
simple_form
. It's currently not possible to simply write `f...
How to query GraphQL APIs with Ruby
While most Rails Apps are tied to at least one external REST API, machine-to-machine communication via GraphQL is less commonly seen. In this card, I'd like to give a quick intro on how to query a given GraphQL API - without adding any additional library to your existing app.
Core aspects of GraphQL
Interacting with GraphQL feels a bit like querying a local database. You are submitting queries to fetch data in a given structure (like SELECT in SQL) or mutations to alter the database (similar to POST/PUT/DELETE in REST). You can ...
Ruby: Retrieving and processing files via Selenium and JavaScript
This card shows an uncommon way to retrieve a file using selenium where JavaScript is used to return a binary data array to Ruby code.
The following code example retrieves a PDF but the approach also works for other file types.
require "selenium-webdriver"
selenium_driver = Selenium::WebDriver.for :chrome
selenium_driver.navigate.to('https://example.com')
link_to_pdf = 'https://blobs.example.com/random-pdf'
binary_data_array = selenium_driver.execute_script(<<-JS, link_to_pdf)
const response = await fetch(arguments[0])
if (!r...