How to access a dmcrypt-encrypted partition from outside your system

This is for you when you want to mount a dmcrypt encrypted partition manually, e.g. from a live CD.

First, open the dmcrypted partition (You need to provide some name. It may, but does not need to, be your LVM group name):

cryptsetup luksOpen /dev/sda5 some_name

Since your encryption container most likely contains an LVM group (root + swap for example), enable the logical volume manager (replace LVM_NAME with your volume group's name):

vgchange -ay LVM_NAME

After that, you can your access (mount, [fsck](https://makandrac...

Authorize allowed values with assignable_values

All our projects have enum-like requirements like this:

  • An attribute value must be included in a given set of values.
  • The list of allowed values must be retrievable in order to render <select> boxes.
  • Each value has a humanized label.
  • Sometimes there is a default value.

Most of the time, this requirement is also needed:

  • The list of assignable values depends on the user who is currently signed in.

In our past projects there are many different solutions for these related requirements, e.g. ChoiceTrait, methods like `available_...

Google Analytics: Changing the tracked URL path

By default, Google Analytics tracks the current URL for every request. Sometimes you will want to track another URL instead, for example:

  • When an application URL contains a secret (e.g. an access token)
  • When you want to track multiple URLs under the same bucket
  • When you want to track interactions that don't have a corresponding URL + request (e.g. a Javascript button or a PDF download)

Luckily the Analytics code snippet allows you to freely choose what path is being tracked. Simple change this:

ga('send', 'pageview');

......

Why has_many :through associations can return the same record multiple times

An association defined with has_many :through will return the same record multiple times if multiple join models for the same record exist (a n:m relation). To prevent this, you need to add ->{ uniq } as second argument to has_many (below Rails 4 it is a simple option: has_many :xyz, :uniq => true).

Example

Say you have an Invoice with multiple Items. Each Item has a Product:

class Invoice < ActiveRecord::Base
  has_many :items
  has_many :products, :through => :items
end

class Item < ActiveRecord::Base
  ...

Issue with an escaped "equals" sign in the development log email representation

An = is represented by =3D in the log file.

I got confused by the leading 3D which is not part of the token, you can see in the following example:

Hallo Max!

Danke f=C3=BCr deinen Beitrag. Bitte best=C3=A4tige deine Teilnahme, inde=
m du auf den folgenden Link klickst:

  http://localhost:3000/beitraege/13/confirm?token=3DEA7BB9DA73FF17AO

Viele Gr=C3=BC=C3=9Fe vom Team!

My token is actually only EA7BB9DA73FF17AO.

Fix warning: Cucumber-rails required outside of env.rb

After installing Bundler 1.1 you will get the following warning when running tests:

WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being defered until env.rb is called.\
To avoid this warning, move 'gem cucumber-rails' under only group :test in your Gemfile

The warning is misleading because it has nothing to do with moving cucumber-rails into a :test group. Instead you need to change your Gemfile to say:

gem 'cucumber-rails', :require => false

Ruby blocks: Braces and do/end have different precedence

TL;DR {} binds stronger than do … end (as always in Ruby, special characters bind stronger than words)

Demo

✔️ Right way

names = ['bRUce', 'STaN', 'JOlIE']

# Blocks in braces are passed to the rightmost method
print names.map { |name| name.downcase }
print(names.map do |name| name.downcase end) # equivalent
=> ["bruce", "stan", "jolie"]

❌ Wrong way

Avoid the examples below, as you pass at least one block to print and not to the enumerator.

names = ['bRUce', 'STaN', 'JOlIE'] 

# Blocks in do…end ar...

MySQL shell: Vertical vs horizontal layout

When talking to your MySQL server via a mysql shell, you can terminate queries by ; or \G -- the latter gives you a vertical output.

You know this:

mysql> SELECT * FROM users;
+----+---------+---------------------+-----------------+
| id | name    | email               | greeting        |
+----+---------+---------------------+-----------------+
|  1 | Alice   | alice@example.com   | Hello world!    |
|  2 | Bob     | bob@example.com     | Hello universe! |
|  3 | Charlie | charlie@example.com | Hi mom!    ...

Ruby: Making your regular expressions more readable with /x and alternative delimiters

The following two hints are taken from Github's Ruby style guide:

If your regular expression mentions a lot of forward slashes, you can use the alternative delimiters %r(...), %r[...] or %r{...} instead of /.../.

 %r(/blog/2011/(.*))
 %r{/blog/2011/(.*)}
 %r[/blog/2011/(.*)]

If your regular expression is growing complex, you can use the /x modifier to ignore whitespace and comments:

regexp = %r{
  start         # some text
  \s            # white space char
  (group)    ...

Show MySQL process list without sleeping connections

Usually you don't need to, but when you want to see which queries your MySQL server currently needs to handle (and if there are locks, etc), you could say SHOW PROCESSLIST in a MySQL shell.

Unfortunately, SHOW PROCESSLIST does not allow filtering. When you are on MySQL ≥ 5.1.7, do this instead:

SELECT * FROM information_schema.processlist WHERE command != 'Sleep' ORDER BY id;

That also allows you to only show some values or order differently, like so:

SELECT user, time, state, info FROM information_schema.processlist WHERE co...

Change how Capybara sees or ignores hidden elements

Short version

  • Capybara has a global option (Capybara.ignore_hidden_elements) that determines whether Capybara sees or ignores hidden elements.
  • Prefer not to change this global option, and use the :visible option when calling page.find(...). This way the behavior is only changed for this one find and your step doesn't have confusing side effects.
  • Every Capybara driver has its own notion of "visibility".

Long version

Capybara has an option (Capybara.ignore_hidden_elements) to configure the default...

MySQL shell: Enable UTF-8

When you do a script/dbconsole -p, your MySQL shell will already be using UTF-8. When you call it yourself using mysql, it may not be enabled.

You'll notice that when you get ASCII salad and/or question marks instead of special characters. \
Example: Hlavn� m?sto Praha instead of Hlavní město Praha.

You need to manually switch on UTF-8, in the MySQL console:

SET NAMES 'utf8';

Capybara: Test that a string is visible as static text

This is surprisingly difficult when there is a <textarea> with the same text on the page, but you really want to see the letters as static text in a <p> or similiar.

The step definition below lets you say:

Then I should see the text "foo"

You should not look too closely at the step definition because when you see the light, it will blind you.

Then /^I should see the text "(.*?)"$/ do |text|
  elements = page.all('*', :text => text).reject { |element| element.tag_name == 'textarea' || element.all('*', :text => text...

Make your Rails console (and irb) output better readable

Pour color on your Rails console with awesome_print. Turn confusing long strings into formatted output. Have objects and classes laid out clearly whenever you need it.

Put gem 'awesome_print', :group => :development into your Gemfile. Now on the Rails console you have the command ap that will give you a colored, formatted output of whatever you pass it. See the example output of the User class below.

For customization visit the repository on Github.

![awesome_print.png](https://makan...

responsive.is

Online tool to test how a site behaves in popular desktop, tablet and phone resolutions.

Spec "content_for" calls in helpers

This only applies to RSpec below version 1.3.2. The issue has been fixed in RSpec 1.3.2, and most likely RSpec 2 and later versions.


When you have a helper that calls content_for and want to check its behavior you should probably write a feature instead. If you still want to do it, mind the following.

Consider this helper:

module LayoutHelper
  def title(string)
    content_for :title, string
    string
  end
end

Somewhere in the layout we'd then say something like this: `<%= yield :title %...</p>

Markdown/Commonmarker examples

This card shows you how to format a card's content using Markdown. We use the Commonmarker interpreter, so here are examples for its dialect.

Formatting

**Bold**

Bold

_Italics_

Italics

`Monospaced`

Monospaced

> Quoted text

Quoted text

Here is [a link](http://makandra.com/).

Here is a link.

![An image; this is the alt text](http:/...

Creating the inverse of a Rails migration

Let's say you need to revert a migration that happened a while back. You'd create a new migration that removes what was added back then in the up path, while its down path restores the old functionality.

While you could just copy&paste the down and up parts of it to the inverse part of the new migration, you may not want to do that. Especially when the up/down paths already contained some logic (that executed update statements on the created column, for example), copying does not feel right.

Someone already added the logic how to...

WebMock 1.8.0 does not play nice with Curb < 0.7.16

When updating WebMock, be prepared that your specs may send real requests into the depths of the internet unless you update Curb as well.\
WebMock will not complain about those requests not being stubbed.

One of the commits that made it into 1.8.0 actually breaks Curb versions below 0.7.16 while fixing it for that version (and above, hopefully).\
WebMock's hooks for Curl::Easy are sti...

Gatekeeping: Guide for developer

If your project manager wants to do gatekeeping on a project, as a developer you need to follow the following guidelines (e.g. by using something like this issue checklist template).

In order to reduce the number of rejects we get from clients, we want to review all code written before it goes to the staging server.


Note: This process is tailored to our specific needs and tools at makandra. While it will certainly not apply to all (especially larger tea...

Gatekeeping: Guide for gatekeeper

If you're responsible for gatekeeping in a projects, here is a guide, what to do.
In order to reduce the number of rejects we get from clients, we want to review all code written before it goes to the staging server.

Note: This process is tailored to our specific needs and tools at makandra. While it will certainly not apply to all (especially larger teams), we think it is a helpful starting point.


First, read the [Gatekeeping for developers](https://makandracards.com/makandra/6579-gatekeeping-guide-for...

ActiveRecord: When aggregating nested children, always exclude children marked for destruction

When your model is using a callback like before_save or before_validation to calculate an aggregated value from its children, it needs to skip those children that are #marked_for_destruction?. Otherwise you will include children that have been ticked for deletion in a nested form.

Wrong way

class Invoice < ApplicationRecord
  has_many :invoice_items
  accepts_nested_attributes_for :invoice_items, :allow_destroy => true # the critical code 1/2
  before_save :calculate_and_store_amount                              # the crit...

What collapsing margins are, how they work and when margins do not collapse

Imagine you have 2 HTML boxes. The first one has a margin-bottom of let's say 30px and the second one a margin-top of 20px. After rules of collapsing margins have been applied we have a margin of 30px (not 50px) between these two boxes . This is because no addition of both margins takes place but the maximum of both is applied. This behavior is called collapsing margins.

Oftentimes it is a good behavior but collapsing margins can be annoying, too. For example child el...

Nicer alternatives to def_delegator or def_delegators

Delegating methods to other objects is often helpful but the syntax of both def_delegators and def_delegator is a complete mess that makes your code hard to read.

Consider these classes:

class Topic < ActiveRecord::Base
  def title
    "A title"
  end
  
  def category
    "Topic category"
  end
end

class Post < ActiveRecord::Base
  belongs_to :topic
  def_delegato...