Rails: Remove Blank Values from Collections
tl;dr
Since Rails
6.1+
you can use.compact_blank
or.compact_blank!
to remove blank values from collections (e.g. arrays).
Remove nil
values from an array
['foo', nil].compact
# => ['foo']
# You can use the splat operator to ignore nil values when constructing an array
['foo', *nil]
# => ['foo']
Remove blank values from collections
Array
array = [1, "", nil, 2, " ", [], {}, false, true]
# Any Rails version
array.reject(&:blank?)
# => [1, 2, true]
# Since Rails 6.1+
array.compact_blank
# ...
Ruby constant lookup: The good, the bad and the ugly
In Ruby, classes and modules are called constants. This card explains how Ruby resolves the meaning of a constant.
The good
E. g. in the following example, Array
could mean either Foo::Array
or simply Array
:
class Foo
def list
Array.new
end
end
What Ruby does here is to see if the name Array
makes sense inside of Foo::
, and if that fails, resolves it to ::Array
(without a namespace).
The bad
This is relevant for old Ruby versions. Ruby 2.5+ removes top-level constant lookup whi...
CSS Support Guide for Email Clients
CSS support in major e-mail clients is horrible.
This will give you an overview what you will not be able to use across all clients.
See also
Postgresql: Paginate and count in one query using window functions
When paginating records, we usually need to know the number of total records in order to render pagination links. Popular pagination libraries like will_paginate or Kaminari do this for us by simply issuing an extra query, like this:
SELECT post.* FROM posts LIMIT 20 OFFSET 100;
SELECT COUNT(*) FROM posts;
This is fine most of the time. But rarely, you might have very complicated WHERE
conditions or a subquery that takes time to run. In thes...
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...
How to solve Selenium focus issues
Selenium cannot reliably control a browser when its window is not in focus, or when you accidentally interact with the browser frame. This will result in flickering tests, which are "randomly" red and green. In fact, this behavior is not random at all and completely depends on whether or not the browser window had focus at the time.
This card will give you a better understanding of Selenium focus issues, and what you can do to get your test suite stable again.
Preventing accidental interaction with the Selenium window
--------------------...
Regex: Be careful when trying to match the start and/or end of a text
Ruby has two different ways to match the start and the end of a text:
-
^
(Start of line) and$
(End of line) -
\A
(Start of string) and\z
(End of string)
Most often you want to use \A and \z.
Here is a short example in which we want to validate the content type of a file attachment. Normally we would not expect content_type_1
to be a valid content type with the used regular expression image\/(jpeg|png)
. But as ^
and $
will match lines, it matches both content_type_1
and content_type_2
. Using \A
and \z
will wo...
Squashing several Git commits into a single commit
This note shows how to merge an ugly feature branch with multiple dirty WIP commits back into the master as one pretty commit.
Squashing commits with git rebase
What we are describing here will destroy commit history and can go wrong. For this reason, do the squashing on a separate branch:
git checkout -b squashed_feature
This way, if you screw up, you can go back to your original branch, make another branch for squashing and try again.
Tip
If you didn't make a backup branch and something ...
You are not using filter_map often enough
Somewhat regularly, you will need to filter a list down to some items and then map them to another value.
You can of course chain map
and compact
, or select
/filter
and map
, but Ruby 2.7 introduced a method for this exact purpose: filter_map
.
So instead of
>> [1, 2, 3, 4, 5, 6].map { |i| i * 2 if i.even? }.compact
=> [4, 8, 12]
or
>> [1, 2, 3, 4, 5, 6].select(&:even?).map { |i| i * 2 }
=> [4, 8, 12]
you can just do
>> [1,...
Josh McArthur: Fancy Postgres indexes with ActiveRecord
I recently wanted to add a model for address information but also wanted to add a unique index to those fields that is case-insensitive.
The model looked like this:
create_table :shop_locations do |t|
t.string :street
t.string :house_number
t.string :zip_code
t.string :city
t.belongs_to :shop
end
But how to solve the uniqueness problem?
Another day, another undocumented Rails feature!
This time, it’s that ActiveRecord::Base.connection.add_index supports an undocumented option to pass a string argument as the v...
ruby-sass: Do not use comments between selector definitions
Sass lets you easily specify multiple selectors at once like this:
.some-block
&.has-hover,
&:hover
outline: 1px solid red
This will add a red outline on either real hover or when the has-hover
class is present. However, adding a comment will void the definition of that line:
.some-block
&.has-hover, // From hoverable.js <-- DON'T
&:hover
outline: 1px solid red
... will simply drop the &.has-hover
part in ruby-sass(deprecated). [sassc](https://rubygems.org/g...
An auto-mapper for ARIA labels and BEM classes in Cucumber selectors
Spreewald comes with a selector_for
helper that matches an English term like the user's profile
into a CSS selector. This is useful for steps that refer to a particular section of the page, like the following:
Then I should see "Bruce" within the user's profile
^^^^^^^^^^^^^^^^^^
If you're too lazy to manually translate English to a CSS selector by adding a line to features/env/selectors.rb
, we already have an [auto-mapper to translate English into ...
How to tackle complex refactorings in big projects
Sometimes huge refactorings or refactoring of core concepts of your application are necessary for being able to meet new requirements or to keep your application maintainable on the long run. Here are some thoughts about how to approach such challenges.
Break it down
Try to break your refactoring down in different parts. Try to make tests green for each part of your refactoring as soon as possible and only move to the next big part if your tests are fixed. It's not a good idea to work for weeks or months and wait for all puzzle pieces ...
Rails: How to find records with empty associations
Imagine these models and associations:
class Deck < ApplicationRecord
has_many :cards
end
class Card < ApplicationRecord
belongs_to :deck, optional: true
end
Now you want to find all Decks without any Card or all Cards without a Deck.
Rails 6.1+
Rails 6.1 introduced a handy method ActiveRecord#missing to find records without given associations.
Deck.where.missing(:cards)
SELECT "decks".*
FROM "dec...
Do not forget mailer previews
When changing code in mailers, updating the corresponding mailer preview is easily forgotten.
Mailer previews can be tested like other code as well and I sometimes add the following test to test suites:
# Make sure to require the previews
Dir[Rails.root.join('spec/mailers/previews/*.rb')].each { |file| require(file) }
ActionMailer::Preview.all.index_with(&:emails).each do |preview, mails|
mails.each do |mail|
describe preview do
specify "##{mail} works" do
expect { preview.call(mail) }.not_to...
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
Project management best practices: Budget control
When starting a project we always make a good estimate of all known requirements, and plan budgets and available developers accordingly.
Requirements change. Budgets usually don't.
To make sure a project stays on track, we update our estimates once a month and compare them to the remaining budget. If this doesn't match any more, we have to act.
To update an estimate, do the following:
- Start with the most recent estimate for the project.
- Which stories have been completed? Set their estimate to zero.
- Have any requirements cha...
Choosing the right gems for your project
Adding a gem means you take over the liability towards the external code.
Checklist
Based on "To gem, or not to gem":
- Gem is really needed (prefer writing your own code for simple requirements without many edge cases)
- Gem is tested well (coverage and quality)
- Gem has a good code quality
- Gem's licence fits to the project requirement
- Try to avoid gems that do much more than your requireme...
IRB's multi-line autocomplete and how to disable it
Recent IRB versions include a multi-line autocomplete which may be helpful to novice users but can be distracting.
Cycling through options works by pressing the Tab key (as usual), and for some methods you also get some kind of documentation, though the quality of results is usually not on par with your IDE of choice.
I have found that it also slows down my IRB in some cases, or that pressing the Backspace key does not always reliably remove characters, which I find more annoying than useful.
You may disable multi-line autocomplete by
- ...
Webpack(er): Analyze the size of your JavaScript components
We're always striving towards keeping our website's JavaScript as small as possible.
If you're using webpack(er), you can use the webpack-bundle-analyzer plugin to get a good overview, which of your JavaScript modules take up how much space, and where you can optimize.
To use it, add it via npm or yarn
yarn add webpack-bundle-analyzer
Then add this to your environment.js
:
// Uncomment this code to show statistics of bundle sizes. Generated file will automatically...
makandra_sidekiq 0.2.0 respects the configured Sidekiq timeout
There was an issue with makandra_sidekiq < 0.2 concerning the stopping of Sidekiq.
Sidekiq < 6 has two finishing timeouts: one for finishing things itself (A), and one for sidekiqctl
before killing a running Sidekiq instance (B). While USAGE banner of sidekiqctl
advises to have B always greater than A, makandra_sidekiq < 0.2 runs sidekiqctl
without passing a timeout. If the Sidekiq instance is configured with a timeout higher than the default 10s timeout of sidekiqctl
, `sideki...
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](...
PSA: Umlauts are not always what they seem to be
When you have a string containing umlauts which don't behave as expected (are not matched with a regexp, can't be found with an SQL query, do not print correctly on LaTeX documents, etc), you may be encountering umlauts which are not actually umlaut characters.
They look, depending on the font, like their "real" umlaut counterpart:
- ä ↔ ä
- ö ↔ ö
- ü ↔ ü
However, they are not the same:
'ä' == 'ä' # false
'ä'.size # 1
'ä'.size # 2
Looking at how those strings are constructed reveals what is going on:
'ä'.unpack('U*...