The Difference Between Width and Flex Basis | Geddski

Within a Flexbox layout, there are multiple CSS attributes that may affect a child's basis (the initial width before flexing). You might be confused how flex-basis, width, min-width and the intrinsic width of your content play together.

The attached article explains the differences. In summary:

  • If a flex-basis is set, that is used as the basis
  • If no flex-basis is set, the width is used as the basis
  • If neither flex-basis nor width is set, the content...

Ruby: __FILE__, __dir__ and symlinks

Ruby's __FILE__ keyword returns the path to the current file. On popular for this are Ruby binaries:

#!/usr/bin/env ruby
$LOAD_PATH << File.expand_path('../../lib', __FILE__)
require 'my_cli'
MyCli.run!

However, if you create a symlink to this file, this will no longer work. __FILE__ will resolve to the path of the symlink, not to its target.

One solution is to use File.realpath(__FILE__).

In Ruby 2+ you can also use this:

$LOAD_PATH << File.expand_path('../lib', __dir__)

__dir__ is simply a shortcut for `...

Stop animations and network polling when the document tab isn't visible

Is your application doing something expensive every few seconds? Maybe an animated slider that rotates images? Maybe you are updating data over the network every five minutes?

It's a good idea to pause this if the your document tab is not even visible to the user. This saves your user's battery and data plan.

You can ask document.visibilityState whether this tab is visible:

function pulse() {
  if (!document.visibilityState || document.visibilityState...

How to quickly inspect an Angular scope in your webkit browser

Current webkit browsers like Chrome and Safari have a special variable in their consoles that refers to the selected DOM node in the elements panel. This lets us easily inspect Angular scopes.

  1. Right click in the page and click "Inspect" to open the Dev Tools

  2. Select the element you're interested in from the elements panel

  3. Focus the console (in Chrome, hit ESC)

  4. Get the scope object and store it

    s=$($0).scope()
    
    // That is:
    element = $0 // Store element
    $element = $(element) // Wrap with j...
    

net-ssh and openssl-3.0.0

You'll need openssl-3 or newer for servers running 22.04

Ruby version 3.1 uses by default the gem openssl-3.0.0. This can cause issues with the gem net-ssh (6.1.0). This is a known bug.

Typically this can cause an error while deploying an application with capistrano:

could not verify server signature (SSHKit::Runner::ExecuteError)

or

Ed25519::VerifyError: signature verification failed!

As temporary workaround add the following line to your Gemfile:

gem 'openssl', ...

RSpec: How to turn off partial double verification temporarily

While verifying doubles in RSpec is a good default, it is limited in the amount of methods it actually is able to verify.

The background is that RSpec can't verify dynamically defined methods, which is a known issue for the usage of helper_method and also the reason why [RSpec >= 3.6](http://rspec.info/blog/2017/05/rspec-3-6-has-been-rel...

Ruby tempfiles

Tempfiles get deleted automatically

With the the ruby Tempfile class you can create temporary files. Those files only stick around as long as you have a reference to those. If no more variable points to them, the GC may finalize the object at some point and the file will be removed from the filesystem. If you would try to access your tempfile then using its path (which you stored previously), you would get an error because the file no longer exists.

Unlink your tempfiles when you're done with them
-...

How to show jQuery event handler on element

Chrome gives you the currently selected element in the inspector with $0. If you select a button in the DOM you can set and inspect the event handler with the following two code lines:

$($0).on('click', function() { console.log('Hello') })
jQuery._data($0, "events").click[0].handler
// => "function () { console.log('Hello') }"

This is useful for debugging.

When upgrading/downgrading RubyGems and Bundler on a server, you must clear bundled gems

On application servers, gems are usually bundled into the project directory, at a location shared across deployments.

This is usually shared/bundle inside your project's root directory, e.g. /var/www/your-project/shared/bundle/.
If you can't find that, take a look at current/.bundle/config and look for BUNDLE_PATH.

When you are changing the version of RubyGems or Bundler on a system where gems are installed this way, you must wipe that bundle directory in addition to the user and system gems or gems that are already ins...

Rails asset pipeline: Why relative paths can work in development, but break in production

The problem

When using the asset pipeline your assets (images, javascripts, stylesheets, fonts) live in folders inside app:

app/assets/fonts
app/assets/images
app/assets/javascripts
app/assets/stylesheets

With the asset pipeline, you can use the full power of Ruby to generate assets. E.g. you can have ERB tags in your Javascript. Or you can have an ERB template which generates Haml which generates HTML. You can chain as many preprocessors as you want.

When you deploy, Rails runs assets:precompile...

How to make RubyMine aware of Cucumber steps defined in gems

If your Ruby project includes a gem like Spreewald that comes with some external step definition, RubyMine does not know about them by default and will highlight the step as an undefined reference:

Image

To link these external step definitions to RubyMine, add the corresponding gems to your RubyMine-Settings:

  • Go to Settings (ctrl + alt + s)
  • Go to Languages and Frameworks
  • Go to Cucumber
  • There, add your gem (e.g "spreewald") via the little "+" from the b...

RSpec: How to define classes for specs

RSpec allows defining methods inside describe/context blocks which will only exist inside them.
However, classes (or any constants, for that matter) will not be affected by this. If you define them in your specs, they will exist globally. This is because of how RSpec works (short story: instance_eval).

describe Notifier do
  class TestRecord
    # ...
  end
  
  let(:record) { TestRecord.new }
  
  it { ... }
end

# TestRecord will exist here, outside of the spec!

This will come bite you at least when you try to define a ...

Flexbox: How to prevent <pre> elements from overflowing

I recently had the problem that embedded code boxes crashed my layout.

It turned out that pres break out of their containers when using them inside a deeper nested flex layout.
For me it was a flex inside a flex item (fleXzibit).

Image

<div class="flex">
  <div class="flex-item">
    ...
    <div class="nested-flex">
      <div class="nested-flex-item">
        <pre>A code example</pre>
      </div>
    </div>
    ...
  </div>
</div>

The reason is that flexbox items default to `mi...

JavaScript: New Features in ES2021

tl;dr

With ES2021 you now can use str.replaceAll(), Promise.any(), logical assignment operators, numeric separators and WeakRef on all major browsers except IE11.

replaceAll

JavaScript's replace(searchValue, replaceValueOrFn) by default replaces only the first match of a given String or RegExp.
When supplying a RegExp as the searchValue argument, you can specify the g ("global") modifier, but you have to remember doing that, hence using replace when you expect global replacement is prone to errors.
When supplying st...

Rails: How to write custom email interceptors

Nowadays it is fairly easy to intercept and modify mails globally before they are sent. All you have to do is register an interceptor class which responds to .delivering_email(message). This card will show you two common use cases.

Subject prefix:

Usually you want to prefix the subject line of emails with the current environment (except production) so you can differentiate between production mails and mails from other environments. Of course a...

Inspect the page content in a Cucumber session

When you need to see the content of a page (i.e. not all the HTML but the relevant text body)

  • you can do pp (html_content)
    • pp will format the html String human readable pretty printed
  • where html_content can be replaced by one of the following commands:

Rails

body or response.body

Capybara:

  • page.driver.html.content
  • page.body

Webrat:

Nokogiri::HTML(response.body).content

The returned strings can be cleaned up by calling .gsub(/^\s*$/, '').squeeze("\n") on them.\
Although this may be useful for d...

Unpoly: Automatically show the full better_errors page when Rails raises an error

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly updates work using AJAX requests, you won't get the more detailled better_errors page with the interactive REPL.

Below is an event listener that automatically repeats the request as a full-page load if your development error shows an error page. This means you get...

Getting different results working with SVG files and ImageMagick

When you are working with SVG files and ImageMagick you can get different results on different machines depending on which additional packages you have installed.

From: http://www.imagemagick.org/script/formats.php

ImageMagick utilizes inkscape if its in your execution path otherwise RSVG. If neither are available, ImageMagick reverts to its internal SVG renderer.

Use DatabaseCleaner with multiple test databases

There is a way to use multiple databases in Rails.
You may have asked yourself how you're able to keep your test databases clean, if you're running multiple databases with full read and write access at the same time. This is especially useful when migrating old/existing databases into a new(er) one.

Your database.yml may look like this:

default: &default
  adapter: postgresql
  encoding: unicode
  username: <%= ENV['DATABASE_USER'] %>
  host: <%= ENV['DATABASE...

ActiveRecord: Query Attributes

tl;dr
You can use attribute? as shorthanded version of attribute.present?, except for numeric attributes and associations.

Technical Details

attribute? is generated for all attributes and not only for boolean attributes.

These methods are using #query_attribute under the hood. For more details you can see ActiveRecord::AttributeMethods::Query.

In most circumstances query_attribute is working like attribute.present?. If your attribute is responding to :zero? then you have to be aware that `query_attri...

How to bind an event listener only once with Unpoly

You can use Unpoly's up.on with a named listener function and immediately unbind this event listener with { once: true }:

up.on('up:fragment:inserted', { once: true }, function () { ... })

In Unpoly 1 you can immediately unregister the listener with up.off:

up.on('up:fragment:inserted', function fragmentInsertedCallback() {
  up.off('up:fragment:inserted', fragmentInsertedCallback)
  // ... code for the callback function, which should run only once
})

Exam...

Gem development: recommended gem metadata

The gemspec for gems allows to add metadata to your gem, some of which have a special meaning and are helpful for users.
You can provide links to your Github bugtracker or changelog file that are then used on the rubygems page of your gem (in the sidebar, e.g. see gem page of consul).

Here are some keys that should be filled:

Gem::Specification.new do |s|
  s.name = 'my-gem'
  s.homepage = 'https://github.com/makandra/my-gem'

  s.metadata = {
    'source_code_uri' => s.homepage,
    'bug_tracker...

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...

Chrome DevTools: List Registered Event Listeners

In Chrome DevTools you can use getEventListeners(object) to get a list of registered event listeners on the specified object.

You can also do this without the console, by selecting an element in the DOM inspector. In the element details, select the tab Event Listeners".

Example

const registry = getEventListeners(document)

registry['up-click']
// 0: { useCapture: false, passive: false, once: false, type: 'up:click', listener: ƒ }
// 1: { useCapture: false, passive: false, once: false, type: 'up:click', listener: ƒ }
//...