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
:visibleoption when callingpage.find(...). This way the behavior is only changed for this onefindand 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.

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.
, 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 teams), we think it...
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...
Run your own code before specific RSpec examples
You probably know about the possibility to tag scenarios in Cucumber to run your own piece of code before the actual scenario is run which looks like that:
@foo
Scenario: Do something
...
and you place the following snippet into support/env.rb:
Before('@foo') do
puts "This is run every time a @foo tagged scenario is hit"
end
You can tag RSpec examples like this:
it 'does something', :foo => true do
...
end
What you need is the following within the RSpec.configure do |config| block wit...
In MySQL, a zero number equals any string
In MySQL comparing zero to a string 0 = "any string" is always true!
So when you want to compare a string with a value of an integer column, you have to cast your integer value into a string like follows:
SELECT * from posts WHERE CAST(posts.comments_count AS CHAR) = '200'
Of course this is usually not what you want to use for selecting your data as this might cause some expensive database operations. No indexes can be used and a full table scan will always be triggered.
If possible, cast the compared value in your application to...