Rails: render a template that accepts a block by using the layout option of render

Let's say you have a form that you render a few times but you would like to customize your submit section each time. You can achieve this by rendering your form partial as layout and passing in a block. Your template or partial then serves as the surrounding layout of the block that you pass in. You can then yield back the form to the block and access the form in your block.

record/_form.haml

= form_for record do |form|
  ...
  .form-actions
    yield(form)
  

In order to make your template record/_form.haml accept a block whe...

How to make Webpacker compile once for parallel tests, and only if necessary

Webpack is the future. We're using it in our latest Rails applications.

For tests, we want to compile assets like for production.
For parallel tests, we want to avoid 8 workers compiling the same files at the same time.
When assets did not change, we do not want to spend time compiling them.

Here is our solution for all that.

Its concept should work for all test suites.

Copy the following to config/initializers/webpacker_compile_once.rb. It will patch Webpacker, but only for the test environment:

# Avoid hardcoded asset host...

How to: Rails cache for individual rspec tests

Rails default config uses the ActiveSupport::Cache::NullStore and disables controller caching for all environments except production:

config.action_controller.perform_caching = false
config.cache_store = :null_store

If you want to test caching you have at least two possibilities:

  1. Enable caching for every test (not covered by this card and straightforward)
  2. Enable caching for individual test

Enable caching for individual test (file cache)

1. Leave the default c...

How to define height of a div as percentage of its variable width

This is useful if, for example, you want to use a background-image that has to scale with the width and the div should only have the height of the picture.

html:

<div class="outer">
  <div class="inner">
  </div>
</div>

css:

.outer {
  width: 100%;
  background-image: image-url('background.png');
  background-size: cover;
}
  
.inner {
  padding-top: 60%;
}

How does it work?

There are several CSS attributes that can handle values as percentage. But they use different other attributes as "reference value...

Middleman: Use pretty URLs without doubling requests

By default Middleman generates files with a .html extension. Because of this all your URLs end in /foo.html instead of /foo, which looks a bit old school.

To get prettier URLs, Middleman lets you activate :directory_indexes in config.rb. This makes a directory for each of your pages and puts a single file index.html into it, e.g. /foo/index.html. This lets you access pages with http://domain/foo.

Don't double your requests!

Unfortunately you are now forcing every br...

Middleman configuration for Rails Developers

Middleman is a static page generator that brings many of the goodies that Rails developers are used to.

Out of the box, Middleman brings Haml, Sass, helpers etc. However, it can be configured to do even better. This card is a list of improvement hints for a Rails developer.

Gemfile

Remove tzinfo-data and wdm unless you're on Windows. Add these gems:

gem 'middleman-livereload'
gem 'middleman-sprockets' # Asset pipeline!

gem 'bootstrap-sass' # If you want to use Bootstrap

gem 'byebug'

gem 'capistrano'
gem 'capistrano-mid...

Solved: Element inside overflow:scroll container cannot be scrolled on iOS when dragged by a contained iframe

Imagine the following HTML structure, where the scrolling container has overflow-y: scroll:

+--scrolling container+-+
|                       |
| +-child element+----+ |
| | ++iframe++        | |
| | |        |        | |
| | |        |        | |
+-----------------------+
  | |        |        |   <-- actually cut off by
  | +--------+        |   <-- scrolling container
  +-------------------+

The issue: On iOS, the child element cannot be scrolled when grabbing the iframe (i.e. putting your finger somewhere on the iframe).
...

How to disable Chrome's save password bubble for Selenium tests

When filling out forms in Selenium tests, Chrome shows the (usual) bubble, asking to store those credentials.

While the bubble does not interfere with tests, it is annoying when debugging tests. Here are two ways to disable it:

Option 1: prefs

You can set profile preferences to disable the password manager like so:

prefs = {
  'credentials_enable_service' => false,
  'profile.password_manager_enabled' => false
}

Capybara::Selenium::Driver.new(app, browser: :chrome, prefs: prefs)

Sadly, there are no command line s...

CSS: Don't target multiple vendor-prefixed pseudo-elements in a single rule

Some pseudo-elements need to be addressed with vendor prefixes. E.g. ::selection is not supported by Firefox, you need to use ::-moz-selection instead.

What you cannot do is to define a single CSS rule to address both the standard and vendor-prefixed form:

::selection, ::-moz-selection {
  background-color: red;
}

This rule will be ignored by all browsers. The reason is that if a browser doe...

How to make http/https requests yourself with nc/telnet/openssl

Sometimes you want/have to send specific http(s) requests. You can do that easy with curl or just write the request yourself.

make a http request with nc

nc example.com 80
GET / HTTP/1.1
Host: example.com
# press enter

make a http request with telnet

telnet example.com 80
GET / HTTP/1.1
Host: example.com
# press enter

make https request with openssl

openssl s_client -connect example.com:443
GET / HTTP/1.1
Host: example.com
# press enter

You can specify more headers if you want:

nc example.c...

How to view Image Metadata on the Linux Command Line with ImageMagick

ImageMagick has a command line tool called identify which can read image metadata:

>identify -verbose DSC00136.JPG
Image: DSC00136.JPG
  Format: JPEG (Joint Photographic Experts Group JFIF format)
  Class: DirectClass
  Geometry: 5472x3648+0+0
  Resolution: 350x350
  Print size: 15.6343x10.4229
  Units: PixelsPerInch
  Type: TrueColor
  Endianess: Undefined
  Colorspace: sRGB
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Channel statistics:
    Red:
      min: 0 (0)
      max: 255 (1)
      mean: 11...

Vim read-only option

You can start vim with a read-only option. This prevents making accidentally changes in files you don't want to touch.

view /file/to/open

view is actually vim.


Use case

You have opened many similar files and accidentally type :wq in the wrong one. Did you make changes? Which changes you made? When do you notice you edited the wrong file?

Beware: Nested Spreewald patiently blocks are not patient

Note: The behaviour of Spreewald's within step is as described below for version < 1.9.0; For Spreewald >= 1.9.0 it is as described in Solution 1.


When doing integration testing with cucumber and selenium you will often encounter problems with timing - For example if your test runs faster than your application, html elements may not yet be visible when the test looks for them. That's why Spreewald (a collection of cucumber steps) has a concept of doing things patiently, which means a given b...

Haml: Prevent whitespace from being stripped in production

Disclaimer

This is not an issue in newer versions of HAML (starting with 5.0.0), as the ugly-option was removed so that in development everything is rendered ugly, too.

Problem

When HTML is rendered from HAML in production or staging environment, whitespace is removed to reduce the download size of the resulting pages. Therefore it might happen that whitespace you see in development is missing in production or staging.

Here is an example of two inlined bootstrap buttons in a t...

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

require 'open3'

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

Bug in Chrome 56+ prevents filling in fields with slashes using selenium-webdriver/Capybara

There seems to be a nasty bug in Chrome 56 when testing with Selenium and Capybara: Slashes are not written to input fields with fill_in. A workaround is to use javascript / jquery to change the contents of an input field.

Use the following code or add the attached file to your features/support/-directory to overwrite fill_in.

module ChromedriverWorkarounds

  def fill_in(locator, options = {})
    text = options[:with].to_s
    if Capybara.current_driver == :selenium && text.include?('/')
      # There is a nasty Bug in Chrome ...

How to search through logs on staging or production environments

We generally use multiple application servers (at least two) and you have to search on all of them if you don't know which one handled the request you are looking for.

Rails application logs usually live in /var/www/<project-environment-name>/shared/log.
Web server logs usually live in /var/www/<project-environment-name>/log.

Searching through single logs with grep / zgrep

You can use grep in this directory to only search the latest logs or zgrep to also search older (already zipped) logs. zgrep is used just like grep ...

Partially disable animations for Angular 1.4+

If you use Angular 1.4+ together with Angular Animate, all ng-show, ng-hide, ng-class etc. are animated on default.

If you want only some elements to be animated there are 2 possibilities: Either disable animations globally and only run animations if the element has a certain class or enable animations globally and add a certain class if no animation is wanted.

Option 1: Enable animations only for html elements with class 'animate'

@app.config ['$animateProvider', ($animateProvider) ->
  $animateProvider.classNameFilter(/\ban...

Git stash: Working with old entries

First find the reference for the entry you want through looking at the stash:

$ git stash list
stash@{0}: WIP on feature/foo
stash@{1}: WIP on feature/bar
stash@{2}: WIP on fix/baz

Now you can simply use that reference, but curly braces must be escaped:

git stash pop stash@\{1\}

or quoted:

git stash apply "stash@{1}"

Quick reminder to [not shoot yourself in the foot](https://makandracards.com/makandra/634-use-the-git-stash-withou...