View

Using local fonts with Webpack / Webpacker

When we want to use our own (or bought) fonts in an application with Webpack(er), we have two options. We can

  • put the fonts directly into your Webpack's assets folder or
  • write an npm package with an own sass file that can be imported from the Webpack manifest.

Load fonts from your assets folder

The first option turns out to be straightforward: Import the stylesheets in the index.js of the pack you're using:

```javascript
// webpack_source_path/application/index.js

import './stylesheets/reset'
import…

How to fix parallel_tests with Redis on powerful machines

When you have a powerful machine with 16 cores, you might run into an error like

Refusing to use Redis db#16

          The Redis DB number should be between 2 and 15, since we're using db#1
          for development and the default Redis config has 16 databases, starting
          with db#0.

The easiest way to fix this is limiting the number of parallel processes that are used in parallel cucumber runs.
To do this, you can set an environment variable in your ~/.bashrc:

 export PARALLEL_TEST_PROCESSORS=14
Repeats

How to fix: Session hash does not get updated when using "merge!"

tl;dr: Do not use merge! for session hashes. Use update instead.

Outline

Let's assume you're modifying the Rails session. For simplicity, let's also assume your session is empty when you start (same effect when there is data):

# In our example, we're in a Rack middleware
request = Rack::Request.new(env)
request.session.merge! :hello => 'Universe'
request.session
=> {}

Wat?

Even worse: When you inspect your request.session like above (e.g. in a debugger shell, o…

Repeats

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 to…

Repeats

Running external commands with Open3

There are various ways to run external commands from within Ruby, but the most powerful ones are Open3.capture3 and Open3.popen3. Since those can do almost everything you would possibly need in a clean way, I prefer to simply always use them.

Behind the scenes, Open3 actually just uses Ruby's spawn command, but gives you a much better API.

Open3.capture3

Basic usage is

```ruby
require 'open3'

stdout_str, error_str, status = Open3.capture3('/some/binary', 'with', 'some', 'args')
if status.success?…

Repeats

Guide to localizing a Rails application

Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.

When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.

Static text

  • Static strings and template text in app must be translated: Screens, mailer templates, PDF templates, helpe…
Repeats

RSpec: How to aggregate failures

RSpec >= 3.3 added aggregate_failures, which allows multiple failures in an example and list them all, rather than aborting on the first failure.

This can be used:

  • In the global configuration
  • With the tag :aggregate_failures (our preferred option in case every expectations should be aggregated)
  • With the method aggregate_failures

Below is an example, which shows why aggregating failures are useful.

Example

```RUBY
aggregate_failures do
firs…

Repeats

Getter and setter functions for Javascript properties

Javascript objects can have getter and setter functions that are called when a property is read from or written to.

For example, if you'd like an object that has a virtual person.fullName attribute that dynamically composes person.firstName and person.lastName:

```
var person = {

firstName: 'Guybrush',

lastName: 'Threepwood',

get fullName() {
return this.firstName + " " + this.lastName;
},

set fullName(name) {
var parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}

};
```…

Auto-destruct in 41 days

Geordi 2.1.0 released

We released two new versions of geordi. See the changelog below for more details.

Note: Geordi 2.0.0 has a breaking change that affects the geordi commit command.

2.1.0 2019-02-25

Compatible changes

  • Fixes [#59]: Removedb name prefix when reading whitelist
  • Fixes [#62]: Provide better error messages on whitelist editing errors.
  • Fixes [#63]: Allow explicit whitelisting of database names that would be considered derivative during db cleanup
  • Fixes [#64]: Remove VISUAL and EDITOR from …
Repeats

How to organize monkey patches in Ruby on Rails projects

As your Rails project grows, you will accumulate a number of small patches. These will usually fix a bug in a gem, or add a method to core classes.

Instead of putting many files into config/initializers, I recommend to group them by gem in lib/ext:

```text
lib/
ext/
factory_girl/
mixin.rb
carrierwave/
change_storage.rb
fix_cache_ids.rb
sanitize_filename_characters.rb
ruby/
range/
covers_range.rb
array/
dump_to_excel.rb
xss_aware_join.rb
enumerable/

Linked contentRepeats

How to explain SQL statements via ActiveRecord

ActiveRecord offers an explain method similar to using EXPLAIN SQL statements on the database.

However, this approach will explain all queries for the given scope which may include joins or includes.

Output will resemble your database's EXPLAIN style. For example, it looks like this on MySQL:

User.where(id: 1).includes(:articles).explain

```
EXPLAIN for: SELECT users.* FROM users  WHERE users.id = 1
+—-+————-+——-+——-+—————+
| id | select_type | table | type  | possible_keys |
+—-+—–…

Repeats

Simple database lock for MySQL

Note: For PostgreSQL you should use an alternative that doesn't require a database table. For MySQL we still recommend the solution in this card.


If you need to synchronize multiple rails processes, you need some shared resource that can be used as a mutex. One option is to simply use your existing (MySQL) database.

The attached code provides a database-based mutex for MySQL. You use it by simply calling

Lock....
Linked content

Copy to clipboard without flash (clipboard.js)

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js because it does not rely on flash. Flash support of the major browsers has ended.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboar…
Linked contentAuto-destruct in 34 days

Updated: Rails routes: Extracting collection actions into their own controllers

In modern Rails versions we can define nested resources in a collection { ... } block to namespace them into an existing resource:

resources :projects, only: :show do
  collection do
    resource :report, only: :show, controller: 'projects/report'
    resources :members, only: [:index, :show]
  end
end

This generates the following routes:

```
GET /projects/:id => ProjectsController#show
GET /projects/report => Projects::ReportsController#show
GET /projects/members => MembersController#index
G…

JavaScript without jQuery (presentation from 2019-01-21)

Summary

  • We want to move away from jQuery in future projects
  • Motivations are performance, bundle size and general trends for the web platform.
  • The native DOM API is much nicer than it used to be, and we can polyfill the missing pieces
  • Unpoly 0.60.0 works with or without jQuery

Is jQuery slow?

```text
From: Sven
To: unpoly@googlegroups.com
Subject: performance on smartphones and tablets

Hello

I just used your framework in one project and must say,
I am really pleased with it – but only on a desktop computer.

Have you benchm…

Linked contentRepeats

Make your Rails console (and irb) output better readable

Pour color on your Rails console with awesome_print. Turn confusing long strings into formatted output. Have objects and classes laid out clearly whenever you need it.

Put gem 'awesome_print', :group => :development into your Gemfile. Now on the Rails console you have the command ap that will give you a colored, formatted output of whatever you pass it. See the example output of the User class below.

For customization visit the repository on Github.

![awesome_print.png](https://makan…

Linked contentRepeats

Rails 4 introduced collection_check_boxes

Starting from Rails 4.0, you can use a special form options helper called #collection_check_boxes. It behaves similar to #collection_select, but instead of a single select field it renders a checkbox and a label for each item in the collection.

= form_for @post do |form|
  = form.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial

How generated form params look like ———————————…

Trigram indexing as an alternative to PostgreSQL fulltext search

For searching in large database tables we usually use PostgreSQL's fulltext search capabilities.

While this works reasonably well for content primarily consisting of prose, it is not necessarily a good solution for all use cases. The main issue is that it is only possible to search for prefixes of text tokens, which can potentially be unexpected for users.

One example are dates:

If you index the text 2019-01-23 15:16, PostgreSQL will create the following tokens: 2019, -01, -23, 15 16. A user searching for 01-23 wi…

This website uses cookies to improve usability and analyze traffic.
Accept or learn more