RSpec: How to check if a string contains terms in a desired order
There seems to be no built-in matcher in RSpec to check if a string contains terms in the desired order. A simple workaround is to use a regular expression that also matches newlines (m
-modifier).
Cons:
- The readability when terms need to be escaped is bad
- A failed spec has an error which needs manually action to be understood (Search if terms appear and in which order)
Example:
expect(ActionMailer::Base.last.to_s).to match(/Dear customer.*Account canceled.*You Awesome Company/m)
An incomplete guide to migrate a Rails application from paperclip to carrierwave
In this example we assume that not only the storage gem changes but also the file structure on disc.
A general approach
Part A: Create a commit which includes a script that allows you to copy the existing file to the new file structure.
Part B: Create a commit which removes all paperclip logic and replace it with the same code you used in the first commit
Part A
Here are some implementation details you might want to reuse:
- Use the existing models to read the files from
- Use your own carrierwave models to write t...
Colcade is a lightweight Masonry alternative
Masonry is a famous library to dynamically arrange a grid of items that have different aspect ratio, like horizontal and vertical images.
Colcade is an alternative masonry-layouting library, developed by the same developer, but with a more modern approach.
It is said to have better performance while being smaller and having no dependencies. It automagically detects jQuery and defines a jQuery initializer, if present.
However, it offers [a few less features](https:...
Pivotal Tracker now supports story description templates
When writing a story description in Pivotal Tracker, there is now a tiny button at the bottom of the description field where you can paste a template.
You can define your own templates by following "More" at the top, then "Templates".
We recommend you define a template following our suggested story description.
Note that the three default templates currently can not be removed or changed.
Faking Flexbox with legacy techniques
Flexbox is great, but you don't get reliable support in Internet Explorer.
The attached article shows how to accomplish many Flexboxish effects without actually using flexbox statements.
The Definitive Guide to Cookie Domains
Restricting access to cookies is essential for security in many web apps. For example, the session ID, the secret token used to identify a particular session, is typically stored in a cookie. Cookies have several important settings. Previously, I discussed the secure flag. This time, let’s dive into the cookie domain.
The cookie domain is an important security feature, probably even more important than the secure flag. It tells the browser that this cookie must only be sent to matching domains. Matching however, can happen in several w...
Minimal JavaScript function to detect version of Internet Explorer or Edge
If possible your code should detect features, not browsers. But sometimes you just need to sniff the browser. And when you do, you're probably fighting a Microsoft product.
The following function returns a Number
like 10, 11, 12, 13 for Internet Explorer or Edge (anything above 11 is Edge). It returns undefined
for any other browser.
function ieVersion(uaString) {
uaString = uaString || navigator.userAgent;
var match = /\...
SSH: X-Forwarding
If you need to run a program on a remote machine (e.g. to your office PC) with a graphical UI (and you trust the remote machine), you can use SSH X-Forwarding. I sometimes use this to connect to a virtual machine installed on my work PC from my home office.
Forwarding X over SSH
To use X forwarding, when connecting to the remote machine, and add -X
to the ssh
call. Now, when you start a program with a UI (e.g. virtualbox
) in that SSH session, a window will open on your local machine. It will not be particularly ...
How to fix: Corrupt special characters in ZIPs on Linux
When you receive a ZIP file from a Windows user, umlauts and other non-latin1 characters in filenames may look corrupt, and probably will be corrupt when extracting the ZIP file.
The reason is encoding: Such archives are probably using Codepage 850. I am serious, 1987 is calling.
Fortunately, the unzip
command can handle such files like so:
unzip -O CP850 file.zip
Interestingly enough, Rubyzip also compresses files that way. Probably so files look alright to Windows users.
Chrome bug: Wrong stacking order when transitioning composited elements
Google Chrome has a subtle rendering bug that hits me once in a while. It usually occurs in sliders with HTML content.
The issue
When a slider contains a composited[1] element, the element will overlap any other element when sliding, being rendered as frontmost element. After the slider has settled, stacking order jumps back to normal.
It seems like Chrome is doing its compositing wrong. This doesn't happen in Firefox.
The cause
The issue only occurs if:
- two elements A and B are nested inside an element C
- A overlaps B (part...
Haml: Generating a unique selector for an element
Having a unique selector for an element is useful to later select it from JavaScript or to update a fragment with an Unpoly.
Haml lets you use square brackets ([]
) to generate a unique class name and ID from a given Ruby object. Haml will infer a class
attribute from the given object's Ruby class. It will also infer an id
attribute from the given object's Ruby class and #id
method.
This is especially useful with ActiveRecord instances, which have a persisted #id
and will hence **generate the same selector o...
Haml: Prefixing a group of attributes
Haml lets you prefix a group of attributes by wrapping them in a hash. This is only possible with the {}
attribute syntax, not with the ()
attribute syntax.
Example: HTML5 data attributes
HTML5 allows you to use arbitrary attributes like data-method
and data-confirm
. You can prefix a group of data-
attributes like this:
%a{href: '/path', data: { method: 'delete', confirm: 'Really delete?' }} Label
This compiles to:
<a data-confirm='Really delete?' data-method='delete' href='/path'>Label</a>
Exa...
3 ways to run Spring (the Rails app preloader) and how to disable it
spring ...
The most obvious way to use spring is to call it explicitly:
spring rails console
spring rake db:migrate
Binstubs
Binstubs are wrapper scripts around executables. In Rails they live inside bin/
. If you run spring binstub --all
, your binstubs will be using Spring.
bin/rails console
bin/rake db:migrate
bundle exec rails ...
Bundle exec
is inconsistent when it comes to spring. Some commands will use it, some won't.
bundle exec rails console # starts Spring...
Debugging Webpacker config
Option 1: JSON dump
In config/webpack/environment.js
you can get inspect environment
which includes all webpack config options set for the current environment:
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
throw JSON.stringify(environment, null, 2)
...
Option 2: Browser console
You can also debug the config in your browser directly with a newer version of Webpacker:
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
...
Introduction to Google Tag Manager (for web developers who know Google Analytics)
As a web developer, you know Google Analytics (GA). Probably you've dropped the GA snippet into more than one website, maybe you've even used its Javascript API to implement tracking at the event level.
Google Tag Manager (GTM) is a related tool, but on a higher level and thus with much more power. GTM is not a replacement for GA. Rather, it can make GA configurable without changing anything in the application's code base (and much more beyond, see below).
Only prefer GTM if the customer requests it, or if he is updating his tracking r...
Rails: Flagging all cookies as secure-only to pass a security audit
Why secure-only cookies used to be necessary
Cookies have an optional secure
flag. It tells the browser to not send the cookie for a non-https request.
It used to be important to activate the secure
flag even on sites that automatically redirect users from http://
to https://
. The reason was that most users will only enter a scheme-less domain like makandra.de
into their location bar, which will default to `http://m...
JavaScript “Stale Practices” | benmccormick.org
The linked article lists a number of techniques that were best practices with ES5, but have better alternatives in modern JavaScript.
Best practices don’t last forever. This is especially true when a field is changing fast, and JavaScript development has changed a lot over the past 10 years. The old best practices go stale, and new ones take their place. Here are 5 JavaScript best practices that have gone stale recently.
Make a local copy of an S3 bucket
To make a local copy of an S3 bucket, I use the s3cmd command line tool.
Configure access keys:
s3cmd --configure
Make a local directory for the backup:
mkdir s3backup
cd s3backup
Get a preview of what we're going to copy:
s3cmd sync --dry-run s3://your-bucket-name-here .
Start copying files:
s3cmd sync s3://your-bucket-name-here .
Fix for Ruby 1.8.7 installation error
On some machines, installing Ruby 1.8.7 with ruby-build can lead to this error:
math.c:37:13: error: missing binary operator before token "("
Try instead to install ruby-1.8.7-p374
.
Heads up: Rails offers two similar means for text truncation
Rails defines a #truncate
helper as well as a method String#truncate
.
= truncate("my string", length: 5)
= "my string".truncate(5)
Both are really similar; in fact, the helper invokes the method and improves it with two niceties: support for passing a block (which could e.g. render a "read on" link), and html_safe
knowledge.
Prefer the truncate() helper
Warning: truncate()
calls html_safe
if you're not escaping. FWIW, an HTML string may easily become invalid when truncated, e.g. when a closing tag gets chopped off.
...
Using the Ruby block shortcut with arguments
Ruby has this handy block shortcut map(&:to_i)
for map { |x| x.to_i }
. However, it is limited to argument-less method invocations.
To call a method with an argument, you usually need to use the full block form. A common and annoying case is retrieving values from a list of hashes (imagine using a JSON API):
users = [ { name: 'Dominik', color: 'blue' }, { name: 'Stefan', color: 'red'} ]
names = users.collect do |user|
user[:name]
end
If you're using Rails 5+, this example is covered by Enumerable#pluck
(`users.pluck(:name)...
Ruby: All Errno::ERROR constants inherit from SystemCallError
To catch all possible exceptions from a network call, we need to rescue
many error classes like this:
rescue SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EHOSTUNREACH, OpenSSL::SSL::SSLError, MyHttpLib::BadResponse
You can shorten this a bit by rescuing SystemCallError
, which is a base class for all Errno::
exceptions:
rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError, MyHttpLib::BadResponse
Some high-level ...
Cucumber steps to travel through time with Timecop
These steps are now part of Spreewald.
Here are some useful examples how to use the attached Cucumber Timecop steps:
When the date is 2011-05-06
When the time is 2011-05-06 17:30
There is also one really awesome step that lets you travel to the past or to the future:
When /^it is (\d+|a|some) (seconds?|minutes?|hours?|days?|months?|years?) (later|earlier)$/
As yo...
Rails' Insecure Defaults - Code Climate Blog
Rails’ reputation as a relatively secure Web framework is well deserved. Out-of-the-box, there is protection against many common attacks: cross site scripting (XSS), cross site request forgery (CSRF) and SQL injection. Core members are knowledgeable and genuinely concerned with security.
However, there are places where the default behavior could be more secure. This post explores potential security issues in Rails 3 that are fixed in Rails 4, as well as some that are still risky. I hope this post will help you secure your own apps, as w...