Project management best practices: The story tracker
In general, the tracker should always be the definitive source of truth of what needs to be done as part of a project. If you identify a task that needs to be done, you should create a story. If you learn something that contradicts an existing story, change it.
The tracker can contain two types of stories: Developer stories, and non-developer stories.
Non-developer stories
Non-developer stories should be clearly marked. They usually belong to the PM (or maybe people from the operations team). Those story can take all forms, could just...
How to make changes to a Ruby gem (as a Rails developer)
At makandra, we've built a few gems over the years. Some of these are quite popular: spreewald (> 1M downloads), active_type (> 1M downloads), and geordi (> 200k downloads)
Developing a Ruby gem is different from developing Rails applications, with the biggest difference: there is no Rails. This means:
- no defined structure (neither for code nor directories)
- no autoloading of classes, i.e. you need to
require
all files yourself - no
active_support
niceties
Also, their scope...
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...
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...
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.
...
Designing HTML emails
The 90s are calling: they want their tables back. Unfortunately, you need them all for laying out your HTML emails.
Email client HTML rendering is way more scattered than browser HTML. While you might have a pretty good understanding of what features and patterns you can use to support all major browsers, I doubt anyone masters this craft for HTML email clients.
The only way to ensure your email looks good (acceptable, at least) in all mail clients, is to check it. Litmus is your go-to solution for this (see below). W...
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)...
Checklist: Rails Authentication
Authentication is a special part of web applications. On the one hand, it usually is a crucial security mechanism restrict access to certain people and roles. On the other hand, most users authenticate only once, so it is very unlikely to spot issues by accident.
So, here comes a quick checklist to help you verifying your authentication solution is all set.
- This should be default: use HTTPS with HSTS. The HSTS part is important.
- Use a reliable authentication solution, e.g. Clearance or [Devise...
Printing background color of elements
Browsers' printing methods usually don't print background colors. In most cases this is the desired behavior, because you don't want to spend tons of ink printing the background of a web page. But in some cases you want to print the background color of elements, e.g. bars of a chart. For those elements you need to set the following CSS styles:
-webkit-print-color-adjust: exact; /* Chrome and Safari */
color-adjust: exact; /* Firefox */
Another case is printing of white text. When removing background colors, chances are white text n...
Rails: Including HTML in your i18n locales
TL;DR
Append your locale keys with _html to have them marked as
html_safe
and translate them with= t('.text_html')
.
When you're localizing a Rails application, sometimes there is this urge to include a little HTML. Be it some localized link, or a set of <em>
tags, you'd like to have it included in the locale file. Example:
# Locale file
en:
page:
text: 'Please visit our <a href="https://www.corporate.com/en">corporate website</a> to learn more about <em>the corporation</em>.'
# HAML
= t('.text')
# D...
Capistrano task to tail remote application logs of multiple servers
When your application is running on a multi-server setup, application logs are stored per server (unless you choose a centralized logging solution).
Here is a Capistrano task that connects to all servers and prints logs to your terminal like this:
$ cap production app:logs
00:00 app:logs
01 tail -n0 -F /var/www/your-application/shared/log/production.log | while read line; do echo "$(hostname): $line"; done
01 app01-prod: Started GET "/sign_in" for 1.2.3.4 at 2018-04-26 11:28:19 +0200
01 app01-prod: Proc...
Unpoly: Loading large libraries on-demand
When your JavaScript bundle is so massive that you cannot load it all up front, I would recommend to load large libraries from the compilers that need it.
Compilers are also a good place to track whether the library has been loaded before. Note that including same <script>
tag more than once will cause the browser to fetch and execute the script more than once. This can lead to memory leaks or cause duplicate event handlers being registered.
In our work we mostly load all JavaScript up front, since our bundles are small enough. We recent...
jQuery: How to replace DOM nodes with their contents
You know that you can use jQuery's text()
to get an element's contents without any tags.
If you want to remove only some tags, but keep others, use contents()
and unwrap()
. Here is how.
Consider the following example element.
$container = $('<div><strong>Hello</strong> <em>World</em></div>')
Let's say we want to discard any <em>
tags, but keep their contents.
Simply find
them, then dive into their child nodes via contents
, and use unwrap
replace their ...
When you want to format only line breaks, you probably do not want `simple_format`
For outputting a given String in HTML, you mostly want to replace line breaks with <br>
or <p>
tags.
You can use simple_format
, but it has side effects like keeping some HTML.
If you only care about line breaks, you might be better off using a small, specialized helper method:
def format_linebreaks(text)
safe_text = h(text)
paragraphs = split_paragraphs(safe_text).map(&:html_safe)
html = ''.html_safe
paragraphs.each do |paragraph|
html << content_tag(:p, paragraph)
end
html
end
Full di...
Rails: How to provide a public link in a mail
Lets say we have a user
with a contract
whereas contract
is a mounted carrierwave file.
Now we want to send the link to the contract in a mail. For this use case join the root_url
with the public contract path in the mailer view:
Plain text email
URI.join(root_url, @user.contract.url)
HTML email
link_to('Show contract', URI.join(root_url, @user.contract.url).to_s)
Note: You need to follow [http://guides.rubyonrails.org/action_mailer_basics.html#g...
Fixing: Gem::Package::PathError: installing into parent path is not allowed
This might be a known issue with Rubygems 2.5.1. This will help:
gem update --system
Generating test images on the fly via JavaScript or Ruby
When you need test images, instead of using services like lorempixel or placehold.it you may generate test images yourself.
Here we build a simple SVG image and wrap it into a data:
URI. All browsers support SVG, and you can easily adjust it yourself.
Simply set it as an image's src
attribute.
JavaScript
Simple solution in modern JavaScript, e.g. for use in the client's browser:
function svgUri(text) {
let svg = `
<svg wid...
How to resize your boot partition when there is an encrypted partition after it
Boot partitions from installations prior to the 16.04 era are terribly small. When you install updates and encounter errors due to a full /boot
partition, consider risizing it.
If you can't do the steps described below, ask someone experienced to help you out.
This has worked 100% so far. 1 out of 1 tries. ;)
Scenario A: There is unassigned space on your physical drive
When there is some unpartitioned space on your drive, increasing the size of /boot
is actually very easy (even though the list below is rather long). It only takes a...
Geordi 1.9 released
New features:
geordi delete_dumps [directory]
Recursively search for files ending in *.dump and offer to delete those. When no argument is given, two default directories are searched for dump files: the current working directory and ~/dumps (for dumps created with geordi).
geordi drop_databases
Delete local MySQL/MariaDB and Postgres databases that are not whitelisted.
Authentication is handled via PAM for Postgres and MariaDB, via .my.cnf
with fallback to mysql -p
for MySQL. Different connection methods can be chosen via ...
Rails: Overriding view templates under certain conditions only
Rails offers a way to prepend (or append) view paths for the current request. This way, you can make the application use different view templates for just that request.
Example
A use case of this is a different set of view templates that should be used under certain circumstances:
class UsersController < ApplicationController
before_action :prepare_views
def index
# ...
end
private
def prepare_views
if <condition>
prepend_view_path Rails.root.join('app', 'views', 'special')
end
end
...
Writing strings as Carrierwave uploads
When you have string contents (e.g. a generated binary stream, or data from a remote source) that you want to store as a file using Carrierwave, here is a simple solution.
While you could write your string to a file and pass that file to Carrierwave, why even bother? You already have your string (or stream).
However, a plain StringIO object will not work for Carrierwave's ActiveRecord integration:
>> Attachment.create!(file: StringIO.new(contents))
TypeError: no implicit conversion of nil into String
This is because Carrierwav...
HTML5: disabled vs. readonly form fields
Form fields can be rendered as noneditable by setting the disabled
or the readonly
attribute. Be aware of the differences:
disabled fields
- don’t post to the server
- don’t get focus
- are skipped while tab navigation
- available for
button
,fieldset
,input
,select
,textarea
,command
,keygen
,optgroup
,option
Browser specific behavior:
- IE 11: text inputs that are descendants of a disabled fieldset appear disabled but the user can still interact with them
- Firefox: selecting text in a disabled text field is no...