Git: Merge a single commit from another branch

This is called "cherry-picking".

git cherry-pick commit-sha1

Note that since branches are nothing but commit pointers, cherry-picking the latest commit of a branch is as simple as

git cherry-pick my-feature-branch

Be aware that cherry-picking will make a copy of the picked commit, with its own hash. If you merge the branch later, the commit will appear in a history a second time (probably without a diff since there was nothing left to do).

Also see our advice for [cherry picking to production branches](https://makandraca...

Automatically validating dependency licenses with License Finder

"Open-source software (OSS) is great. Anyone can use virtually any open-source code in their projects."

Well, it depends. Licenses can make things difficult, especially when you are developing closed-source software. Since some OSS licenses even require the employing application to be open-sourced as well (looking at you, GPL), you cannot use such software in a closed-source project.

To be sure on this, we have developed a project-level integration of Pivotal's excellent [license_finder](https:/...

How to prevent Nokogiri from fixing invalid HTML

Nokogiri is great. It will even fix invalid HTML for you, like a browser would (e.g. move block elements out of parents which are specified to not allow them).

>> Nokogiri::HTML.fragment("<h1><p>foo</p><span>bar</span></h1>").to_s
=> "<h1></h1><p>foo</p><span>bar</span>"

While this is mostly useful, browsers are actually fine with a bit of badly formatted HTML. And you don't want to be the one to blame when the SEO folks complain about an empty <h1>.

To avoid said behavior, use Nokogiri::XML instead of Nokogiri::HTML whe...

FactoryBot: Traits for enums

FactoryBot allows to create traits from Enums since version 6.0.0

The automatic definition of traits for Active Record enum attributes is enabled by default, for non-Active Record enums you can use the traits_for_enum method.

Example

factory :user do
  traits_for_enum :role, %w[admin contact] # you can use User::ROLES here, of course
end

is equivalent to

factory :user do
  trait :admin do
    role { 'admin' }
  end

  trait :contact do
    role { 'c...

The HTML5 video element

# Basic HTML example
<video poster="preview_image.png" controls>
  <source src="or_here.webm" type="video/webm" />
  <source src="alternative_if_browser_cant_pay_first_source.mp4" type="video/mp4" />
  <track src="optional_subtitles.vtt" kind="subtitles" srclang="de" label="Deutsch" default>
</video>

# Javascript API (notable methods and properties)
video = document.querySelector('video')
video.play()
video.pause()
video.load() // Reset to the beginning and select the best available source
video.currentSrc // The selected source
video.c...

The JavaScript Object Model: Prototypes and properties

Speaker today is Henning Koch, Head of Development at makandra.

This talk will be in German with English slides.

Introduction

As web developers we work with JavaScript every day, even when our backend code uses another language. While we've become quite adept with JavaScript at a basic level, I think many of us lack a deep understanding of the JavaScript object model and its capabilities.

Some of the questions we will answer in this talk:

  • How does the new keyword construct an object?
  • What is the differen...

Merging two JavaScript objects

Let's say you want to merge the properties of two JavaScript objects:

let a = { foo: 1, bar: 2 }
let b = { bar: 3, baz: 4 }

let merged = merge(a, b) // => { foo: 1, bar: 3, baz: 4 }

Depending on your build, there are several ways to implement merge().

When you have ES6

When you have an ES6 transpiler or don't support IE11, you may use the spread operator (...) to expand both objects into a new object literal:

let merg...

PostgreSQL: Difference between text and varchar columns

PostgreSQL offers three character types for your columns:

  • character varying(n) (also called varchar or just string): Contents are limited to n characters, smaller contents are allowed.
  • character(n): All contents are padded with spaces to allocate exactly n characters.
  • text: There is no upper or lower character limit (except for the absolute maximum of 1 GB).

The documentation states:

There is no performance difference among these three types, apart ...

Select2 alternatives without jQuery

Select2 is a fantastic library for advanced dropdown boxes, but it depends on jQuery.

Alternatives

Tom Select

There is a selectize.js fork called Tom Select. It is well tested, comes with Bootstrap 3, Bootstrap 4 and Bootstrap 5 styles and is easy to use. You might miss some advanced features.

Known issues:

  • Dynamic opt-groups in AJAX requests are not supported, you need to define them in advance on the select field (see <https://github.com/selectize/selectize.js/pull/1226/...

How to use Active Job to decouple your background processing from a gem

In a web application you sometimes have tasks that can not be processed during a request but need to go to the background.
There are several gems that help to you do that, like Sidekiq or Resque.

With newer Rails you can also use ActiveJob as interface for a background processing library. See here for a list of supported queueing adapters.
For ...

Howto: Select2 with AJAX

Select2 comes with AJAX support built in, using jQuery's AJAX methods.
...
For remote data sources only, Select2 does not create a new element until the item has been selected for the first time. This is done for performance reasons. Once an has been created, it will remain in the DOM even if the selection is later changed.

If you have a huge collection of records for your select2 input, you can populate it via AJAX in order to not pollute your HTML with lots of <option> elements.

All you have to do is to provide...

Testing for XSS in Markdown Fields

If you render markdown from user input, an attacker might be able to use this to inject javascript code into the source code of your page.
The linked github page is a collection of common markdown XSS payloads which is handy for writing tests.

Producing arbitrary links:

[Basic](javascript:alert('Basic'))
[Local Storage](javascript:alert(JSON.stringify(localStorage)))
[CaseInsensitive](JaVaScRiPt:alert('CaseInsensitive'))
[URL](javascript://www.google.com%0Aalert('URL'))
[In Quotes]('javascript:alert("InQuotes")')

Using onload...

Error handling in DOM event listeners

When an event listener on a DOM element throws an error, that error will be silenced and not interrupt your program.

In particular, other event listeners will still be called even after a previous listener threw an error. Also the function that emitted the event (like element.dispatchEvent() or up.emit()) will not throw either.

In the following example two handlers are listening to the foo event. The first handler crashes, th...

Don't ever use the float type for database columns

Like in any language, a FLOAT will eventually corrupt data due to rounding errors.

Please use DECIMAL, which has well-defined behavior for rounding and range overflows.

Ruby: Using the pry debugger in projects with older Ruby versions

In case you want to use pry with an older version of Ruby, you can try the following configurations.

Ruby 1.8.7

Your pry version must not be greater than 0.9.10.

gem 'pry', '=0.9.10'
gem 'ruby-debug', '=0.10.4'
gem "ruby-debug-pry", :require => "ruby-debug/pry"
gem 'pry-nav'
gem 'ruby18_source_location'

Ruby 1.9.3

Your pry version must not be greater than 0.9.9.

gem 'debugger', '=1.1.4'
gem 'pry-debugger', '=0.2.0'
gem 'pry', '=0.9.9'

Known errors

No source for ruby-1...

The ultimate guide to Ruby timeouts

An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.

Here’s how to add timeouts for popular Ruby gems. All have been tested. You should avoid Ruby’s Timeout module. The default is no timeout, unless otherwise specified. Enjoy!

Migrate data between Redis servers

There is a reasonable simple way to move data between Redis servers: Simply temporarily configure the new server as a replica of the old server.

To do this:

  1. Make sure the new Redis server can access the old server. If they are on different networks, a simple SSH tunnel will do.
  2. Connect to the new server using redis-cli.
  3. Tail the log of the redis server (found in /var/logs/redis) in another terminal.
  4. Make sure the server is currently master and not already a replica (check INFO replication)
  5. Enable replication with `REPL...

Nokogiri: CSS syntax for XML namespaces

<soapenv:Envelope>
  <soapenv:Body>
    <elem>
      <nest>...</nest>
    </elem> 
  </soapenv:Body>
</soapenv:Envelope>

CSS selectors are a very simple tool to select elements from a Nokogiri document. However, the colon in the XML namespace syntax does not work with CSS. When selecting namespaced elements, you need to replace their colon (soapenv:Envelope) with a pipe (soapenv|Envelope):

document = Nokogiri::XML(xml)
nest = document.at_css 'soapenv|Envelope soapenv|Body elem nest'

Cucumber may complain about cucumber.yml being invalid when it is valid

Running Cucumber tests while your cucumber.yml is 100% valid may still produce the following error.

cucumber.yml was found, but could not be parsed. Please refer to cucumber's documentation on correct profile usage.

This may in fact be due to your rerun file (e.g. tmp/rerun.txt) being invalid. Delete it and try again.

Legacy CarrierWave: How to generate versions with different file extensions

We use CarrierWave in many of our projects to store and serve files of various formats - mostly images. A common use case of CarrierWave's DSL is to "process" the original file in order to create multiple "versions", for example different resolutions of the same image.

Now we could go one step further: What if we want to create versions that have a different file extension than the original file? For example, let's assume we'd like to create a ve...

How Rails and MySQL are handling time zones

When working with times and dates in Rails applications, you need to deal with the following problem:

  • In Rails, Time objects have a time zone. You can get the zone name by doing time_object.zone.
  • This zone is considered when doing time calculations, e.g. 10 AM CEST minus 8 AM UTC is zero.
  • A datetime in MySQL does not have a zone. It just stores the literal string "2010-05-01 12:00:00".
  • That means that Rails must make assumptions about timestamps loaded from and written to MySQL.

Rails has two completely different modes ...

You don't need each, collect or select in Coffeescript

Working with lists in Javascript is painful because the native Array class is so poorly designed.

One way to reduce the pain is to to use Underscore.js's functions like _.each, _.map or _.select, which unfortunately clutters your code with awkward calls to the _ helper.

Fortunately when you use CoffeeScript you don't need any of that. CoffeeScript has a very versatile for keyword that can do anything that each, collect or select can do. Enjoy!

each

f...

Rspec: How to write better specs

betterspecs.org is a documentation on how to write better RSpec tests.

Note that there are also other approaches like The Self-Contained Test, which is complementary to the dry-approches in betterspecs. Like usual you need to weight the different recommendation and there is no rule of thumb for all specs.

How to reset a Mock

With Rspec you can mock objects or functions, for example like this:

expect(my_object).to receive(:my_function).and_return('hello world')

It's also easy to remove mocks for an object:

RSpec::Mocks.space.proxy_for(my_object).reset