open-next-failure: An alias to speed up test debugging
Getting an entire test suite green can be a tedious task which involves frequent switches between the CLI that is running tests back to the IDE where its cause can be fixed.
The following bash aliases helped me speed up that process:
alias show-next-failure="bundle exec rspec --next-failure"
alias open-next-failure="show-next-failure || show-next-failure --format json | jq -r '.examples[0]' | jq '\"--line \" + (.line_number|tostring) + \" \" + .file_path' | xargs echo | xargs rubymine"
There is a lot going on above but the gist...
When does Webpacker compile?
Webpack builds can take a long time, so we only want to compile when needed.
This card shows what will cause Webpacker (the Rails/Webpack integration) to compile your assets.
When you run a dev server
While development it is recommended to boot a webpack dev server using bin/webpack-dev-server.
The dev server compiles once when booted. When you access your page on localhost before the initial compilation, the page may load without assets.
The ...
How Rails chooses error pages (404, 500, ...) for exceptions
When your controller action raises an unhandled exception, Rails will look at the exception's class and choose an appropriate HTTP status code and error page for the response.
For instance, an ActiveRecord::RecordNotFound will cause Rails to render a red "The page you were looking for doesn't exist" with a status code of "404" (not found).
The mapping from exception classes to error types is a hash in Rails.configuration.action_dispatch.rescue_responses. The...
Test your application's e-mail spam scoring with mail-tester.com
You can use mail-tester.com to check your application's e-mails for issues that might cause e-mails to be classified as spam.
They provide a one-time e-mail addresses that you can use to sign up etc. You can then check for scoring results of SpamAssassin and other potential issues.
You don't need to hit 10/10. Something around 9/10 is perfectly fine.
Note:
- For password-protected staging sites you will get an error for links that can not be resolved. This is fine, simply check production once available.
- ...
Devise: Invalidating all sessions for a user
Background information about session storage in Rails
Rails has a default mechanism to store the session in the CookieStore. This is a cookie which holds the entire user session hash in the browser. This cookie is serialized, encoded with base64, and signed.
How Devise handles authentication
Devise uses this CookieStore. To track a users session, a salt is stored in the session ...
Capistrano: creating a database dump if migrating
In Capistrano 3, your Capfile requires 'capistrano/rails/migrations', which brings two Capistrano tasks: deploy:migrate and deploy:migrating. The former checks whether migrations should be performed. If so, the latter is invoked, which performs the actual migrations.
Knowing this, it is easy to dump the db only if migrations will run. First, enable conditional migrations:
# config/deploy.rb
set :conditionally_migrate, true # Only attempt migration if db/migrate changed
Then hook up the dump task to deploy:migrating:
How to auto-rotate document (text based) images before OCR or computer vision tasks
A page scanned upside down or sideways has the potential to confuse OCR engines and vision LLMs. While both are often capable of handling such inputs, the overall extraction quality tends to be better when we pass in only input with correctly oriented text.
Detecting and correcting the image orientation does not require extra hardware on our web servers, it just adds a bit of complexity to the overall pipeline.
Approach
Tesseract ships with an [Orientation and Script Detection (OSD)](https://tesseract-ocr.github.io/tessdoc/ImproveQuali...
Customize your Bash prompt
The shell variable PS1 holds your bash prompt. You might want to change it to serve your needs best. Here is how to:
General
- non-printing escape sequences in your prompt have to be inclosed in
\[\e[and\]so your shell can correctly count its prompt's length - we recommend to highlight your prompt on production machines
- you can also [show different root prompts for each user](https://makandracards.com/makandra/9569-get-the-username-w...
Deliver Paperclip attachments to authorized users only
When Paperclip attachments should only be downloadable for selected users, there are three ways to go.
The same applies to files in Carrierwave.
Variant: Deliver attachments through Rails
The first way is to store Paperclip attachments not in the default public/system, but in a private path like storage inside the current release. You should prefer this method when dealing with sensitive data.
...
Use Time.current / Date.current / DateTime.current on projects that have a time zone
Basically, you now need to know if your project uses a "real" time zone or :local, and if config.active_record.time_zone_aware_attributes is set to false or not.
-
With time zones configured, always use
.currentforTime,Date, andDateTime.ActiveRecord attributes will be time-zoned, and
.currentvalues will be converted properly when written to the database.
Do not useTime.nowand friends. Timezone-less objects will not be converted properly when written to the database. -
With no/local time zone use
Time.now, `...
How to make Webpacker compile once for parallel tests, and only if necessary
Webpack is the future. We're using it in our latest Rails applications.
For tests, we want to compile assets like for production.
For parallel tests, we want to avoid 8 workers compiling the same files at the same time.
When assets did not change, we do not want to spend time compiling them.
Here is our solution for all that.
Its concept should work for all test suites.
Copy the following to config/initializers/webpacker_compile_once.rb. It will patch Webpacker, but only for the test environment:
# Avoid hardcoded asset host...
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
Gemfileforwebpacker - Remove version locks in
package.jsonforwebpackandwebpack-dev-server - Install by ca...
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](...
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...
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.watchInputDelay. 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](https://gi...
Lightning Talk: Coverage based Test Case Prioritization in Ruby on Rails
For my computer science bachelor's thesis I programmed and evaluated a CLI Test Case Prioritization (TCP) tool for makandra. It has been written as a Ruby Gem and was tested and evaluated against one Ruby on Rails project. This card will summarize and present the research results, the evaluation and the programmed CLI tool.
The code has been published for educational purposes on GitHub. The german bachelor's thesis has also been included for download at the end.
...
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 ("deployment target").
Installing jobs only for a given Rails environment
-----------------------------------...
Using CSS transitions
CSS transitions are a simple animation framework that is built right into browsers. No need for Javascript here. They're supported by all browsers.
Basic usage
Transitions are used to animate the path between to property values. For example, to let the text color fade from red to green on hover, the following SASS is used (shorthand syntax):
.element
color: red
transition: color .1s
&:hover
color: green
This tells the browser "whenever the color of an .element changes...
Rails: Testing exceptions with the rescue_responses setting
In Rails 7.2 the new default for config.action_dispatch.show_exceptions is rescuable.
-
:rescuable: It will show a Rails error page in the response only for rescuable exceptions as
defined byActionDispatch::ExceptionWrapper.rescue_responses. In the
event of an unexpected internal server error, the exception that caused
the error will still be raised within the test so as to provide a useful
stack trace and a good debugging experience. -
:all: It wi...
MySQL replication how-to
This may be awkward to set up, but will work once you're done.
Fun facts:
- In case of a connection loss the slave will try to reconnect to the master server and resume replication for the next 24 hours
- If you want to use your slave as a "real" MySQL server, you basically need to switch off replication (
STOP SLAVE; RESET SLAVE;and reset your my.cnf) and restart the MySQL daemon.
Master server configuration
-
- Create replication user
- In the MySQL shell:
CREATE USER 'replicator'@'%' IDENTI...
Shell script to magically configure display setup
Here is a bash script that I use to auto-configure displays on Ubuntu 24.04 with Xorg.
Background
- Ubuntu always sets the primary display to the 1st (i.e. internal) display whenever I connect to a new Dock/Hub.
- I want my primary display to be the large display.
- My notebook is always placed left of external displays, so the 2nd display will be the center (or only) external display and should be primary.
- I also want all my displays to be placed horizontally, but bottom-aligned (the default would be aligned at their top edges)....
Too many parallel test processes may amplify flaky tests
By default parallel_tests will spawn as many test processes as you have CPUs. If you have issues with flaky tests, reducing the number of parallel processes may help.
Important
Flaky test suites can and should be fixed. This card is only relevant if you need to run a flaky test suite that you cannot fix for some reason. If you have no issues...
Middleman configuration for Rails Developers
Middleman is a static page generator that brings many of the goodies that Rails developers are used to.
Out of the box, Middleman brings Haml, Sass, helpers etc. However, it can be configured to do even better. This card is a list of improvement hints for a Rails developer.
Gemfile
Remove tzinfo-data and wdm unless you're on Windows. Add these gems:
gem 'middleman-livereload'
gem 'middleman-sprockets' # Asset pipeline!
gem 'bootstrap-sass' # If you want to use Bootstrap
gem 'byebug'
gem 'capistrano'
gem 'capistrano-mid...
Migrating from Elasticsearch to Opensearch: searchkick instructions (without downtime!)
General
A general overview about why and how we migrate can be found under Migrating from Elasticsearch to Opensearch
This card deals with specifics concerning the use of searchkick.
Step 1: Make Opensearch available for Searchkick
In your Gemfile
# Search
gem 'searchkick' # needs to be > 5, to use Opensearch 2
gem 'elasticsearch'
gem 'opensearch-ruby'
in config/initializers/searchkick.rb (or wherever you have configured your Searchkick settings) add:
SEARCHKICK_CLIENT_T...