Avoid exceptions for typecasting to integer
There's a method Integer() defined on Kernel
, that typecasts everything into an Integer.
Integer("2") # 2
Integer(nil) # Can't convert nil to Integer (TypeError)
Integer([]) # Can't convert Array into Integer (TypeError)
Integer(Object.new) # Can't convert Object into Integer (TypeError)
Integer(2) # 2
Integer("11", 2) # 3
This is very similar but not identical to to_i
:
"2".to_i # 2
nil.to_i # 0
[].to_i # undefined method 'to_i' for an instance of Array (N...
Automatic Log Rotation in Rails
Rails log files rotate automatically when they reach approx. 100MB:
$ ls -lh log/
-rw-r--r-- 1 user group 55M Sep 15 09:54 development.log
-rw-r--r-- 1 user group 101M Aug 22 13:45 development.log.0
This behavior is a built-in feature of Ruby's standard Logger
class, which Rails uses by default.
To control the maximum file size, set config.log_file_size
in your environment configuration. This is useful for keeping log files man...
Checklist: Rails Authentication
Authentication is a special part of web applications. On the one hand, it usually is a crucial security mechanism restrict access to certain people and roles. On the other hand, most users authenticate only once, so it is very unlikely to spot issues by accident.
So, here comes a quick checklist to help you verifying your authentication solution is all set.
- This should be default: use HTTPS with HSTS. The HSTS part is important.
- Use a reliable authentication solution, e.g. Clearance or [Devise...
Documenting your Rails project's Node.js version in .nvmrc
Not all versions of Node.js are compatible with each other. Also npm packages may require a minimum or maximum version of Node.js. We use nvm on our development PCs so we can operate multiple versions of Node.js in parallel.
To make sure that all developers use a compatible version of Node.js, your Rails project should declare the required Node.js in a file called .nvmrc
.
When a .nvmrc
exists, developers can cd
in your project directory and activate...
Organize large I18n dictionary files in Ruby on Rails
If you're suffering from a huge de.yml
or similiar file, cry no more. Rails lets you freely organize your dictionary files in config/locales
.
My organization works like this:
-
config/locales/rails.de.yml
modified Rails boilerplate -
config/locales/faker.de.yml
modified Faker boilerplate -
config/locales/models.de.yml
model names, attribute names, assignable_value labels - `config/locales/views.de.y...
Bookmarklet to generate a Pivotal Tracker story from Zammad Ticket
This is a bookmarklet you can add to Chrome or Firefox which will allow you to create a story in Pivotal Tracker from a Zammad ticket. This might come in handy when creating stories for SWAT Teams.
But first you will have to set two variables in the script below:
-
pt_project_id
: the ID of the Pivotal Tracker Project you want to add stories to. This can be found as part of the URL of the project (https://www.pivotaltracker.com/n/projects/<pt_project_id>
) -
pt_token
: the Pivotal Tracker token used for authentication. Can be found in y...
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(...) ...
Reliably sending a request when the user leaves the page
navigator.sendBeacon
is a way to reliably send a POST request, even on unload.
Please note, however, that there are generally two ways to detect a "user leaving the page":
- The
unload
event, which fires after a page is actually gone (e.g. after tab close, page refresh, and navigation away). - The
visibilitychange
event. It is much softer, and will fire after tab contents have been hidden by any means (e.g. when closing a tab, but also when switchin...
Stabilize integrations tests with flakyness introduced by Turbo / Stimulus / Hotwire
If you run a Rails app that is using Turbo, you might observe that your integration tests are unstable depending on the load of your machine. We have a card "Fixing flaky E2E tests" that explains various reasons for that in detail.
Turbo currently ships with three modules:
- Turbo Drive accelerates links and form submissions by negating the need for full page reloads.
- Turbo Frames decompose pages into independent contexts, which scope navigation and can be lazily loaded.
- T...
What does 100% mean in CSS?
The attached article examines what the percent unit (%
) is relative to in CSS
The article does a great job of visualizing the dependencies. The TLDR is:
Own property | % of |
---|---|
height |
parent height |
width |
parent width |
top |
parent height |
left |
parent width |
margin-top |
parent width |
margin-left |
parent width |
padding-top |
parent width |
padding-left |
parent width |
How to avoid multiple versions of a package in yarn
To avoid multiple versions of a package, you can manually maintain a resolutions
section in your package.json
. We recommend you to do this for packages like jQuery. Otherwise the jQuery library attached to window
might not include the functions of your packages that depend on jQuery.
Note: This is only an issue in case you want to use a package functionality from window
e.g. $(...).datepicker()
from your dev console or any other javascript within the application.
Background
By default yarn will create a folder node_modules
...
Processing GitLab Merge Requests within RubyMine
GitLab has a RubyMine plugin that enables you to review and process merge requests within RubyMine!
Setup
- Open RubyMine settings (Ctrl + Alt + S) > Plugins > Search for "GitLab" > Install
- (You might need to re-open settings afterwards.)
- In the RubyMine settings > Version Control > GitLab > Connect your GitLab account with "+"
Working with merge requests
- From the Actions menu (Ctrl + Shift + A), choose "View merge...
Rails: Redirecting the Logger output temporary aka showing Rails logs in the console
Most of the time, when you are interested in any log output,
- you see the logs directly on your console
- or you tail / grep some logfile in a separate terminal window
In rare cases it's helpful to redirect the Logger output temporary to e.g. STDOUT
.
Rails.logger = Logger.new(STDOUT)
ActiveRecord::Base.logger = Logger.new(STDOUT)
User.save!
#=> D, [2025-09-08T11:12:26.683106 #1094157] DEBUG -- : User Load (1.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1 [["LIMIT", 1]]
Many frameworks in Rails ...
Colorful output for several linux command line tools: grc
Because colors improve readability so much.
On Ubuntu 18.04 you can install it with sudo apt install grc
From github:
For the impatient - try following commands:
grc netstat
grc ping hostname
grc tail /var/log/syslog
grc ps aux
How to evaluate CSS media queries in JavaScript
To make CSS rules dependent on the screen size, we use media queries:
@media (max-width: 500px) {
// rules for screen widths of 500px or smaller
}
Browsers will automatically enable and disable the conditional rules as the screen width changes.
To detect responsive breakpoints from JavaScript, you may use the global matchMedia()
function. It is supported in all brow...
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/...
Disable SimpleCov if you only run a fraction of your tests
Coverage reports are rarely useful if you run only small parts of your test suite.
Just do not load SimpleCov in this case, and you will see less noise in your test output:
if RSpec.configuration.files_to_run.count > 5
require "simplecov"
SimpleCov.start 'rails'
end
See also
Javascript: How to match text by Unicode properties
The linked MDN article is quite informative of a neat feature supported by all major browsers: Unicode character class escape.
You can use it to write regular expressions that work on the full UTF-8 space, not just Latin/ASCII. For example, a password policy matcher might include regular expressions like [A-z]
or [0-9]
, but those do not match e.g. German umlauts or [Eastern Arabic Numerals](https:/...
ActiveRecord: Named bindings in conditions
In Active Record you can use named bindings in where
-conditions. This helps you to make your code more readable and reduces repetitions in the binding list.
Example without named bindings
User.where(
'name = ? OR email = ?',
params[:query],
params[:query]
)
Example with named bindings
User.where(
'name = :query OR email = :query',
query: params[:query]
)
Capybara will not find links without an href attribute
Capybara and most assistive technology will fail to find <a>
tags that are missing an href
attribute. This will probably happen to you every now and then on JavaScript-heavy applications.
An example would be an AngularJS application where the following HTML actually works. [1]
<a ng-click="hello()">Hello</a>
Capybara will fail to find that link, even though looking it up via the DOM shows it:
>> find_link("Hello")
Capybara::...
Don't define a controller action called #process
Remember that your controller actions share the same method space with private methods defined in ActionController::Base
. If your controller behaves in super-weird ways, check that you don't overwrite some internal method with a controller action.
Examples for internal methods:
#process
#process_action
#cookies
#params
#request
#response
Debugging
If you accidentally did overwrite some internal method, you may come across an ArgumentError
with the message `wrong number of arguments (given 1, expe...
Updated: Integrating ESLint
Updated the instructions for ESLint to work with version 5.x.
Improve accessibility with [aria-required] in SimpleForm
SimpleForm comes with an option browser_validations
which could be used to give fields that have a presence validation the HTML required attribute. We usually turn it off due to difficulties controlling its behavior and appearance. Instead we only mark required fields with an asterisk (*) next to its label. Blind users probably only discover the validation issue after submitting the form due to the now displayed error messages.
A compromise with better acce...
RSpec: Marking sections in long examples
RSpec examples can get quite long, especially in feature specs. This makes them hard to read & understand. Also, when executing them, it may take seconds to see any progress.
To improve this, I have successfully been using a little "step" helper in my tests. It marks semantic sections, structuring an example while improving documentation. When the test runs, each step prints its message (or a dot, depending on your formatter).
# spec/support/step_helper.rb
module StepHelper
# Use this helper to label groups of related actions in l...