Use rbenv-each to run a command for every installed Ruby version
The linked rbenv plugin rbenv-each is very helpful to keep QoL gems up to date that are not part of the Gemfile.
For example, you can bump the geordi version for all your rubies with the following command:
rbenv each gem update geordi
Another useful example would be to bulk-update bundler or rubygems.
Note that rbenv-each hasn't been updated since 2018, but it is fully functiona...
Don't use log level :debug in your production environments
Catch phrase
You don't want sensitive user data in your logs.
Background
Rails per default filters sensitive data like passwords and tokens and writes [FILTERED] to the logs. The code which is responsible for enabling that usually lives in filter_parameter_logging.rb (Rails.application.config.filter_parameters). Here is an example of a filtered log entry:
Unfiltered:
`User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."token" = $1 LIMIT $2 [["token", "secret-token"], ["LIMIT", 1]]`
After the filter is appl...
Split your parallel tests by execution time and keep execution logs up to date
Both knapsack and parallel_tests have the option to split groups by historic execution time. The required logs for this might be outdated since you manually have to update and push them into your repository.
The following card includes an option how you can keep them consistently up to date with no extra effort locally and/or remotely.
How to always split by execution logs
Parallel Tests
The parallel_tests gem has the option flag `--group...
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.
...
Do not pass params directly into url_for or URL helpers
Rails' url_for is useful for generating routes from a Hash, but can lead to an open redirect vulnerability.
Your application's generated route methods with a _url suffix are also affected because [they use url_for unter the hood](https://github.com/rails/rails...
CarrierWave: Processing images with libvips
When you write your next CarrierWave uploader, consider processing your images with libvips instead of ImageMagick.
Reasons for libvips
There are several upsides to using libvips over ImageMagick:
- libvips is considerably faster and uses less memory.
- ImageMagick has a large attack surface that has repeatedly caused security incidents in the past (compare [ImageMagick CVEs](https://www....
RubyMine: Fixing "Rubocop returned exit code -1. See the logs for details"
When RubyMine reports Rubocop returning "exit code -1", upgrading Rubocop can be the fix:
gem install rubocop
"The logs" can be accessed with Ctrl + Shift + A > Show log in (Files). This opens your file manager at the IDEA log location; the log file is called "idea.log".
If your operating system supports it, right click into the file manager > Open in Terminal. There run tail -f idea.log to follow the log.
Best practice: How to manage versions in a Gemfile
It most cases it's not necessary to add a version constraint next to your gems in the Gemfile. Since all versions are saved in the Gemfile.lock, everyone running bundle install will get exactly the same versions.
There are some exceptions, where you can consider adding a version constrain to the Gemfile:
- You are not checking in the
Gemfile.lockinto the version control (not recommended) - A specific gem has a bug in a more recent version (adding a comment for the reason is highly recommended)
- You want to ensure no one upgrade...
Local deployment after pipeline succeeds
If you have a fully functional CI pipeline but no CD, you might find yourself frequently waiting for CI (with "merge after pipeline succeeds") just to perform the deployment.
The following command waits for the next commit that lands on the current branch (should be main or similar) and proceeds to deploy staging afterwards:
alias await-deployment='watch -g git pull && bundle exec cap staging deploy'
Note
Use at your own risk.
You could be deploying code from someone else that was pushed to the same branch in the meantime.
Code splitting in esbuild: Caveats and setup
Code splitting is a feature of esbuild that can keep huge libraries out of the main bundle.
How code splitting works
Like Webpack esbuild lets you use the await import() function to load code on demand:
// application.js
const { fun } = await import('library.js')
fun()
However, esbuild's code splitting is disabled by default. The code above would simply inline (copy) `l...
Find Where a Rake Task is Defined
You can use rake --where task to find the source location that defines task:
bundle exec rake --where assets:precompile
rake assets:precompile /home/henning/.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/precompiled_assets-0.2.1/lib/precompiled_assets/tasks/assets.rake:5:in `block in <main>'
Chromedriver: Connect local chromedriver with docker
Debugging your integration tests, that run a headless Chrome inside a docker image, is tricky.
In many cases you can connect your Chrome to a remote docker container like docker-selenium, which should be the preferred way when you try to inspect a page within your integration test.
Otherwise you might be able to start your docker container with --net=host and access your local chromedriver in the host address space host.docker.internal.
If both options above don't work for you here is a...
Fast rubocop autocorrection alias
The rubocop binary has a few interesting flags:
-
rubocop(using the--paralleldefault ) scans the current repository for linting issues while using multiple CPU cores -
rubocop -a(or--autocorrect) safely corrects most offenses while doing a sequential scan -
rubocop -A(or--autocorrect-all) also tries to correct unsafe suggestions
Autocorrection takes significantly longer on large projects because of the sequential nature.
To speed things up, you can use the following alias. It first checks in parallel if any files...
Rails: Fixing ETags that never match
Every Rails response has a default ETag header. In theory this would enable caching for multiple requests to the same resource. Unfortunately the default ETags produced by Rails are effectively random, meaning they can never match a future request.
Understanding ETags
When your Rails app responds with ETag headers, future requests to the same URL can be answered with an empty response if the underlying content ha...
ASDF: A Version Manager To Rule Them All
tl;dr
asdfallows you to manage multiple runtime versions with a single CLI tool and is backwards compatible by supporting existing config files, like e.g..nvmrcor.ruby-version.
Getting Started
- Disable rbenv
1.1 Delete or comment outsource /home/$user/.rbenvrcin~/.profile
1.2 Delete or comment oureval "$(rbenv init -)"in~/.bashrcor~/.zshrc
1.3 To take effect you may have to restart your shell or log out and log in again from your current linux session - Install asdf by following the official ...
Rails: Your index actions probably want strict_loading
By activating strict_loading you force developers to address n+1 queries by preloading all associations used in the index view. Using an association that is not preloaded will raise an ActiveRecord::StrictLoadingViolationError.
I think it's a good default to activate strict_loading in your controllers' #index actions. This way, when a change introduces an n+1 query, you...
How to enable template coverage support for simplecov
Since Ruby 3.2.0 you can measure coverage support for eval statements and support has been added for the simplecov gem as well.
This allows to track coverage across ruby templates such as haml, erb, ...
Simply set this within simplecov
SimpleCov.start do
enable_coverage_for_eval
end
SASS: Reusing styles from other files
SASS has an @extend keyword to inherit styles.
.alert
color: red
&.-framed
border: 1px solid red
padding: 5px
&.-homepage
@extend .-framed
border-width: 5px
When compiling, SASS will simply join the selectors. Note how .-homepage is written where .-framed was defined:
...
.alert.-framed, .alert.-homepage {
border: 1px solid red;
padding: 5px;
}
.alert.-homepage {
border-width: 5px;
}
Warning
Unfortunately, this does...
Heads up: Deployment with newly generated SSH key (using ED25519) might fail
If you use a newer SSH key generated with the ED25519 algorithm instead of RSA (see Create a new SSH key pair), the deployment with Capistrano may fail with the following message:
The deploy has failed with an error: unsupported key type `ssh-ed25519'
net-ssh requires the following gems for ed25519 support:
* ed25519 (>= 1.2, < 2.0)
* bcrypt_pbkdf (>= 1.0, < 2.0)
See https://github.com/net-ssh/net-ssh/issues/565 for more information
Gem::LoadError : "ed25519 i...
Rails: Using database default values for boolean attributes
In the past we validate and set default values for boolean attributes in Rails and not the database itself.
Reasons for this:
- Older Rails didn't support database defaults when creating new records
- Application logic is "hidden" in the database
An alternative approach, which currently reflects more the general opinion of the Rails upstream on constraints in the database, is adding default values in the schema of the database itself. We also ...
git: find the version of a gem that releases a certain commit
Sometimes I ran across a GitHub merge request of a gem where it was not completely obvious in which version the change was released. This might be the case for a bugfix PR that you want to add to your project.
Git can help you to find the next git tag that was set in the branch. This usually has the name of the version in it (as the rake release task automatically creates a git tag during release).
git name-rev --tags <commit ref>
Note
The more commonly used
git describecommand will return the last tag before a c...
Fixing wall of net/protocol warnings
After upgrading to Rails 6.1.7.2 one of our apps printed a wall of warnings while booting:
/var/www/app/shared/bundle/ruby/2.6.0/gems/net-protocol-0.2.1/lib/net/protocol.rb:68: warning: already initialized constant Net::ProtocRetryError
/home/deploy-app/.rbenv/versions/2.6.10/lib/ruby/2.6.0/net/protocol.rb:66: warning: previous definition of ProtocRetryError was here
/var/www/app/shared/bundle/ruby/2.6.0/gems/net-protocol-0.2.1/lib/net/protocol.rb:214: warning: already initialized constant Net::BufferedIO::BUFSIZE
/home/deploy-app/.rben...
Bundler 2.3 honors the version specified in `BUNDLED_WITH`
Bundler so far ignored the version specified under BUNDLED_WITH in the Gemfile.lock. This had two annoying consequences:
- If the bundler version on your system was lower than in the
Gemfile.lock, you got an error message and had to manually install the correct version. - If the bundler version on your system was higher than in the
Gemfile.lock, bundler silently updated the version in theGemfile.lockto your system's bundler version. To avoid this, you had to always specify, which version you want to use for each bundler c...
Timecop: reset after each test
Timecop is a great gem to set the current time in tests. However, it is easy to introduce flakyness to your test suite when you forget to reset the time after the test.
This might be the case if:
- a test freezes time and a later test does not work for frozen time
- a later test needs the real current date to work correctly
Often you only notice these kinds of errors in rare cases when tests are executed in a particular order.
A way to avoid this is by using block notation (`Timecop.travel(...) ...