Generated face images for UI mockups

Generated Photos produces AI-generated face images.

This is useful for UI mockups where you don't want to show real people or copyrighted stock photography.

VCR and the webdrivers gem

If you're using the webdrivers gem and VCR together, depending on your configuration, VCR will yell at you regulary.
The webdrivers gem tries to update your webdrivers on your local machine. To do so, it checks the internet for newer versions, firing an HTTP-request to e.g. https://chromedriver.storage.googleapis.com

You can "fix" this in multiple ways:

  1. Update your drivers on your machine with
    RAILS_ENV=test rake webdrivers:chromedriver:update

  2. Ignore the driver update-URL in your ...

Rails: How to list all validations on a model or an attribute

If a model inherits from others or uses many concerns / traits, it might be hard to see in the code which validators it has.
But fortunately there's a method for that:

irb(main):002:0> pp UserGroup.validators
[#<ActiveModel::Validations::InclusionValidator:0x00007f55efff97a8
  @attributes=[:deleted],
  @delimiter=[true, false],
  @options={:in=>[true, false], :allow_nil=>false}>,
 #<ActiveModel::Validations::InclusionValidator:0x00007f55f15748d0
  @attributes=[:cancelled],
  @delimiter=[true, false],
  @options={:in=>[true, false], ...

Simple form examples with bootstrap

Good reference how to build bootstrap forms with simple_form.

Always, always declare your associations with symbols

Never ever declare your associations with a string, especially when doing metaprogramming. A common mistake is something like

# WRONG
class Page < ActiveRecord::Base
  %w[main sub].each do |type|
    belongs_to "#{type}_title"
  end
end

   
# RIGHT
class Page < ActiveRecord::Base
  %w[main sub].each do |type|
    belongs_to :"#{type}_title"
  end
end

Always convert to a symbol, otherwise you'll have all [kinds](/m...

How to include Sidekiq job IDs in Rails logs

When logging in Rails, you can use the log_tags configuration option to add extra information to each line, like :request_id or :subdomain. However, those are only valid inside a request context and have no effect when your application is logging from inside a Sidekiq process.
This includes custom as well as any framework logs, like query logging from ActiveRecord.

Since Sidekiq Workers run inside threads of a single process, running multiple jobs in...

Pagy

Pagy is a gem for pagination.
They make some bold claims:

Pagy is the ultimate pagination gem that outperforms the others in each and every benchmark and comparison.

Maybe this is worth trying out.

How to generate GIDs from an ActiveRecord scope

ActiveRecord provides the ids method to pluck ids from a scope, but what if you need to pluck Global IDs?

While you could just call map(&:to_global_id) on your scope, this approach would instantiate each record just to do that. When you have many records, this will at the very least be slow.

Here is a method that does it for you efficiently. It respects Single Table Inheritance (STI).
Put it in your project's ApplicationRecord to make it available on all models.

class ApplicationRecord
  ...

Chrome: Using browser notifications

Development

Google Chrome disables Notifications for insecure origins (i.e. those using HTTP). Only http://localhost is considered secure.

If you need to use browser notifications on other origins, you can set a flag: chrome://flags/#unsafely-treat-insecure-origin-as-secure. Enable the flag and add your origins. Remember that "origin" refers to the combination of protocol+hostname+port, e.g. "http://example.com:8088".

Git: Search for text in all branches

To find a version containing the regular expression foo in the history of any branch:

git grep foo $(git rev-list --all)

You may also limit the search to a file extension, e.g. Ruby files (.rb) like this:

git grep foo $(git rev-list --all) -- *.rb

Ruby Jard: Just Another Ruby Debugger

Ruby Jard provides a rich Terminal UI that visualizes everything your need, navigates your program with pleasure, stops at matter places only, reduces manual and mental efforts.

Workflow: How to use a key management service to encrypt passwords in the database

This is an extract from the linked article. It shows an approach on how to implement encrypted passwords with the AWS Key Management Service (KMS).

For most applications it's enough to use a hashed password with a salt (e.g. the gem devise defaults to this).

Upon password creation

  1. Generate hash as hash of password + salt.

  2. Encrypt the hash with a public key from KMS (you can store the public key in your server code).

  3. In your database sto...

Carrierwave: How to migrate to another folder structure

A flat folder structure can be cool if you have only a few folders but can be painful for huge amounts. We recently had this issue in a project with more than 100.000 attachments, where we used a structure like this /attachments/123456789/file.pdf.

Even the ls command lasted several minutes to show us the content of the attachments folder.

So we decided to use a more hierarchical structure with a limited maximum of folder per layer. Here are a few tips how to migrate your files to their new...

How to fix: Rails query logs always show lib/active_record/log_subscriber.rb as source

Rails 5.2+ supports "verbose query logs" where it shows the source of a query in the application log.
Normally, it looks like this:

  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE ...
  ↳ app/controllers/users_controller.rb:42:in `load_users'

However, you may encounter ActiveRecord's LogSubscriber as the source for all/most queries which is not helpful at all:

  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE ...
  ↳ activerecord (6.0.3.3) lib/active_record/log_subscriber.rb:100:in `debug'

While th...

Fixing AfterAll TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This error occurs when passing an object instead of a string to Jasmine's describe():

# Bad
describe(HoverClass, function() { ... })

# Correct
describe('HoverClass', function() { ... })

Service Worker series by GoMakeThings

Learn how to create offline applications with service workers.

  1. The amazing power of service workers
  2. Writing your first service worker with vanilla JS
  3. Saving recently viewed pages offline with service workers and vanilla JS
  4. Offline first with service workers and vanilla JS
  5. Improving web font performance with service workers
  6. How to set an expiration date for items in a service worker cache
  7. How to update a service worker
  8. How to trigger a service worker function from the front end with vanilla JS
  9. How to immediately ...

RubyMine: Restore main menu in Ubuntu

After a recent Ubuntu update I didn't see the main menu bar of the RubyMine IDE (File | Edit | View | ...) anymore.

This could be solved by changing a RubyMine registry entry:

  • Search "registry" within the "Actions" search
    • press ctrl + alt + n > click on Actions > type registry > click on Registry...
  • Scroll down to linux.native.menu and disable the checkbox

After rebooting RubyMine, you'll have gotten the menu bar back.

Cucumber 4 and VCR integration

If you are trying to integrate VCR and Cucumber 4 and you're using the use_scenario_name: true option you will run into an error like this:

undefined method `feature' for #<Cucumber::RunningTestCase::TestCase:0x00005650550ba080>

Currently the VCR integration and Cucumber 4 is broken, but you can find an open issue with details and a monkey patch here.

apt: how to prevent a package from upgrading

Sometimes new versions of software introduce new bugs. In this case you might not want the package to upgrade on a simple apt upgrade run. To do so, you can set the package on hold.

Hold a package:

sudo apt-mark hold <package-name>

Remove the hold:

sudo apt-mark unhold <package-name>

Show all packages on hold:

sudo apt-mark showhold

When you set a package on hold and you run apt upgrade you will see the following output which will remind you of the hold:

...
The following packages have been kept back:
...

Clean your Rails routes: grouping

In Ruby on Rails, all the routes of a given application can be found within the config/routes.rb file.
You add more and more routes in this file as your project grows.

The problem here is that this file potentially becomes very complicated to manage over the time.
That’s why it’s important to find a way to order and maintain your routes.

See: Clean your Rails routes: grouping

Sometimes the routes.rb grows very fast and each line adds mo...

Ruby: Appending lines to a file in sync

When writing some logs to a file, that don't use Ruby's logger utility, it is often useful to sync them. So other process can read the output just in time.

Example with enabled sync

log_path = '/tmp/some_log.log'

log_file = File.open(log_path, 'a+')
log_file.sync = true

log_file.puts('Some log message')
File.read(log_path) #=> "Some log message\n"

log_file.puts('Some other message')
File.read(log_path) #=> "Some log message\nSome other message\n"

Example ...

Webpacker: Disable source maps

You can do this per environment, e.g. in config/webpack/test.js:

const environment = require('./environment')
const config = environment.toWebpackConfig()
config.devtool = 'none'
module.exports = config

Parallel cucumber: How to pass in cucumber arguments

Here is an example with the --tags option. You need to wrap them inside --cucumber-options option of parallel_cucumber.

DISPLAY=:17 bundle exec parallel_cucumber --cucumber-options '--tags @solo' features

See more details in the docs.

Useful Ruby Pathname method

If you have a Ruby Pathname, you can use the method :/ to append filepaths to it.

With this method, Ruby code can look like this:

Rails.root/"features"/"fixtures"/"picture.jpg"

Alternatively you can use the #join method, which feels less magic:

Rails.root.join('features', 'fixtures', 'picture.jpg')