View

Redis Sentinel manual failover

  1. Connect to your sentinel instance:

    redis-cli -p <SENTINEL-PORT>
    
  2. Have a look at the current master and the available slaves

    SENTINEL masters
    
    SENTINEL slaves <master name>
    
  3. Force a failover

    SENTINEL failover <master name> 
    
  4. After some seconds you can have a second look at the current master:

    SENTINEL masters
    

    The IP should have changed.

FactoryGirl: Passing attributes to associated records using transient attributes

```ruby
FactoryGirl.define do

factory :parent do
transient do
child_name nil
child_allowed_to_drive false
end

child do
  create(:child, name: child_name, allowed_to_drive: child_allowed_to_drive)
end   end

factory :child do
name 'Child'
allowed_to_drive false
end

end

Usage

daughter = FactoryGirl.create(:parent, child_name: 'Lisa').child
daughter.name # => 'Lisa'
daughter.allowed_to_drive? # => false

son = FactoryGirl.create(:parent, child_name: 'Benedikt', child_allowed_to_drive: true…

How Rails chooses error pages (404, 500, ...) for exceptions

When your controller action raises an unhandled exception, Rails will look at the exception's class and choose an appropriate HTTP status code and error page for the response.

For instance, an ActiveRecord::RecordNotFound will cause Rails to render a red "The page you were looking for doesn't exist" with a status code of "404" (not found).

The mapping from exception classes to error types is a hash in Rails.configuration.action_dispatch.rescue_responses. The…

Repeats

count vs. size on ActiveRecord associations

TLDR

  • When counting records in an association, you should use #size in most cases.
  • It will not work if the parent record has never been saved. Also there are finer distinctions between #size and #count. See below.

count

  • Always makes a COUNT(*) query if a counter cache is not set up.
  • If a counter cache is set up on the association, #count will return that cached value instead of executing a new query.

size, if the association has already been loaded

  • Counts elements in the already loaded array.
  • Does not …
Repeats

Stop animations and network polling when the document tab isn't visible

Is your application doing something expensive every few seconds? Maybe an animated slider that rotates images? Maybe you are updating data over the network every five minutes?

It's a good idea to pause this if the your document tab is not even visible to the user. This saves your user's battery and data plan.

You can ask document.visibilityState whether this tab is visible:

```
function pulse() {
if (!document.visibilityState || document.visibilityState =…

Repeats

Find an ActiveRecord by any column (useful for Cucumber steps)

The attached patch lets you find a record by a string or number in any column:

User.find_by_anything('carla')
User.find_by_anything('email@domain.de')
User.find_by_anything(10023)

There's also a bang variant that raises ActiveRecord::NotFound if no record matches the given value:

User.find_by_anything!('carla')

Boolean and binary columns are excluded from the search because that would be crazy.

I recommend copying the attachment to features/support/find_by_anything.rb, since it is most useful in Cucumber step …

Middleman does not fingerprint asset paths by default

We're using Middleman for some static sites like our blog.

Despite being very similar to Rails, Middleman does not add a fingerprint hash to its asset paths by default. This means that when you write this:

<%= javascript_include_tag 'all.js' %>

… you always get the same path, regardless of the contents of all.js:

<script src='/javascripts/all.js'>

Because browsers tend to cache assets for a while, this means that users might not get your changes until their cac…

Repeats

What edge_rider gives you

edge_rider is Power tools for ActiveRecord relations (scopes). Please note that some of the functions edge_rider provides have native implementations in newer rails versions.

Relation#traverse_association(*names)

Edge Rider gives your relations a method #traverse_association which returns a new relation by "pivoting" around a named association. You can traverse multiple associations in a single call. E.g. to turn a relation of posts into a relation of all posts of their authors:

```
posts…

External content

The Current State of Telephone Links | CSS-Tricks

The linked article shows what current browsers do when you click a link like this:

<a href="tel:1-562-867-5309">1-562-867-5309</a>

Spoiler: The current state is sad

It's still the case that most desktop browsers can't do something useful with tel: links. They will usually open a dialog confirming that an external application will be opened. If the user confirms, she will see an error, or nothing at all.

On mobile browsers on the other hand, these links just open…

Repeats

Guide to localizing a Rails application

Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.

When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.

Static text

  • Static strings and template text in app must be translated: Screens, mailer templates, PDF templates, helpe…

Represent astral Unicode characters in Javascript, HTML or Ruby

Here is a symbol of an eight note: ♪

Its two-byte hex representation is 0x266A.

This card describes how to create a string with this symbol in various languages.

All languages

Since our tool chain (editors, languages, databases, browsers) is UTF-8 aware (or at least doesn't mangle bytes), you can usually get away with just pasting the symbol verbatim:

note = '♪'

This is great for shapes that are easily recognized by your fellow programmers.
It's not…

Repeats

Checklist for implementing authentication

This card has four sections, concerning

  • all apps behind SSL
  • apps employing Clearance
  • apps with basic authentication
  • apps with home-made, self-built authentication

Choose what applies to you.

For any application that stores sensitive data in the browser, that is, cookies (e.g. by offering a login)

  • Ask the admins to turn on SSL (they will set an HSTS header for SSL-only sites)
  • [Make cookies secure and http_only](https://makandracards.com/makand…
External contentRepeats

How Googlebot Crawls Javascript

Google seems to have made some progress with indexing Javascript-heavy sites.

Note that we haven't verified any of this. Also there are other important search engines than Google, especially outside of Germany/Europe.

About Piwik

Piwik is the leading open-source analytics platform.

As such, it is an alternative to Google Analytics. Since it is open-source, it can be self-hosted and thus offers better data protection and privacy.

Notes

Actuality
Piwik does not show live reports, but updates its reports from time to time. piwik.pro seems to generate reports only once an hour. The exception to this is the dashboard, where you have a "Visitors in Real-time" widget that will show live tracking actions.
Date
Piwik analytics is always for a specific date (ra…
Repeats

Custom error messages in RSpec or Cucumber steps

Sometimes you have a test expectation but actually want a better error message in case of a failure. Here is how to do that.

Background

Consider this test:

User.last.should be_present

In case of an error, it will fail with a not-so-helpful error message:

expected present? to return true, got false (Spec::Expectations::ExpectationNotMetError)

Solution

That can be fixed easily. RSpec expectations allow you to pass an error message like this:

User.last.should be_present, 'Could not find a user!'

Now your test will…

Repeats

Case sensitivity in PostgreSQL

PostgreSQL, unlike MySQL, treats strings as case sensitive in all circumstances.

This includes

  • comparison with = and LIKE
  • collision detection in unique indexes

Usually this is fine, but some strings (like emails and usernames) should typically be treated as case insensitive.

There are a few workarounds available:

  • use the citext extension
  • use ILIKE instead of LIKE
  • use Postgres' lower() function
  • add an index on lower(email)

Probably the best approach is…

Repeats

ActiveRecord: validate_uniqueness_of is case sensitive by default

By default, validates_uniqueness_of does not consider "username" and "USERNAME" to be a collision. If you use MySQL this is probably not what you want.

(If you use PostgreSQL, read this instead.)

Say you have a user model

class User < ActiveRecord::Base
  validates_uniqueness_of :name
end

with a unique index in the database.

If you try to create the users "user" and "USER", this will not trigger a validation error, but may fail with a SQL error due to duplicate index key.

You can change Rails' behaviour, by…

Repeats

How to find out what is running on a port on a remote machine

By convention, common protocols use a defined port, like 80 for HTTP or 443 for HTTPS.

You can use nmap to find out what service is running behind a given port, and most often see some details about it.
This can be helpful if servers don't offer the services you expect for some ports.

Note that nmap's service discovery may trigger several requests.

Example

When using nmap, adding the -A switch will make nmap discover details about the given port. Specify that port using -p.

Here we look at port 443 on makandracards.com:

``…

View
3222 cards