PostgreSQL: How to add/remove/modify array values (and how to replace 1 value with multiple values)

PostgreSQL's array data type is pretty useful, but manipulating values of arrays can be awkward because of its syntax.

Consider the following users table which each example below will start from:

name topics
Alice {cats,dogs}
Bob {llamas}

(PostgreSQL uses curly braces to represent arrays, true story.)

Adding values

Use the array_cat function, or the || operator.

These calls will add the values "cats" and "mice" to use...

How to disable Rails raising errors on pending migrations in development

Rails 4 introduced raising an error on pending migrations. This is most annoying when you are crafting a migration but need to play with your application to figure out how to do it.

To disable this behavior, just set the corresponding config option to false:

# in config/environments/development.rb

# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = false # was :page_load

Web Fonts Performance // Speaker Deck

Web fonts are great. They are also be really bad for front-end performance because they block rendering. You may have experienced this on a slow cellular network. Staring at a blank page is no fun, especially when the content has already loaded.

This talk explores why browser have placed fonts on the critical path, and how we can work around this while still delivering a good user experience. It also takes a look at what the future will bring to web font performance: preloading hints, the font-display property, and HTTP/2.

Keeping web applications fast

Our applications not only need to be functional, they need to be fast.

But, to quote Donald Knuth,

premature optimization is the root of all evil (or at least most of it) in programming

The reasoning is that you should not waste your time optimizing code where it does not even matter. However, I believe there are some kinds of optimizations you should do right away, because

  • they are either obvious and easy
  • or they are very hard to do optimize later

This is an attempt to list some of those things:

On the server

...

Recommended Git workflow for feature branches

This is a guide on how to effectively use Git when working on a feature branch. It is designed to get out of your way as much as possible while you work, and ensure you end up with clean commits in the end.

We assume you are the only person working on this branch. We also assume the branch has never been "partially" merged into master.

You want to start a feature branch

git checkout master
git checkout -b my-feature-branch
git push -u origin my-feature-branch

You've added code that works ind...

Enumerators in Ruby

Starting with Ruby 1.9, most #each methods can be called without a block, and will return an enumerator. This is what allows you to do things like

['foo', 'bar', 'baz'].each.with_index.collect { |name, index| name * index }
# -> ["", "bar", "bazbaz"]

If you write your own each method, it is useful to follow the same practice, i.e. write a method that

  • calls a given block for all entries
  • returns an enumerator, if no block is given

How to write a canonical each method

To write a m...

OR-ing query conditions on Rails 4 and 3.2

Rails 5 will introduce ActiveRecord::Relation#or. On Rails 4 and 3.2 you can use the activerecord_any_of gem which seems to be free of ugly hacks and nicely does what you need.

Use it like this:

User.where.any_of(name: 'Alice', gender: 'female')

^
SELECT "users".* FROM "users" WHERE (("users"."name" = 'Alice' OR "users"."gender" = 'female'))

To group conditions, wrap them in hashes:

User.where.any_of({ name: 'Alice', gender: 'female' }, { name: 'Bob' }, { name: 'Charl...

pgAdmin has a "graphical EXPLAIN" feature

When working with PostgreSQL, you can use pgAdmin as a GUI.
While you can do most things just like on an SQL console, you can use it to display EXPLAIN results in a more human-readable way.


(image from the Postgres manual)

  1. Open up pgAdmin, connect to your server
  2. Pick a database from the left pane
  3. Click the "SQL" icon in the toolbar, or press Ctrl+E to open the query tool.
  4. Paste any queries that you'd like to explain.
  5. Go to "Query" → "Explain analyze", or ...

Escape a string for transportation in a URL

To safely transport an arbitrary string within a URL, you need to percent-encode characters that have a particular meaning in URLs, like & or =.

If you are using Rails URL helpers like movies_path(:query => ARBITRARY_STRING_HERE), Rails will take care of the encoding for you. If you are building URLs manually, you need to follow this guide.

Ruby

In Ruby, use CGI.escape:

# ✅ good
CGI.escape('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"

Do not ever use `URI.en...

Improving browser rendering performance

As the web is being used for more and more tasks, expectations rise. Not only should web pages offer rich interaction, they must be responsive in both size and interaction.

This imposes a paradoxon that needs to be solved by building performing applications. It's not enough any more to have your web site do crazy stuff, it is also required to do it crazy fast. This card is intended to give you an introduction to this emerging aspect of web development.

Read this introductory [performance study on Pinterest](http://www.smashingmagazine.com/...

Project management best practices: User stories & Issues

We organize our daily work with issues in our Linear workspace.

Issue format

A good issue needs to be precise. It should be very clear what is part of an issue, and what is not. If there are different expectations between the person who writes and who implements an issue, there will be rejects.

To this end, we use a consistent format for issues that looks like this:

Issue: Autocomplete

As a journalist, I want to have an autocomplete in the search bar, to have a more efficient way to find articles.

Acceptance criteri...

Project management best practices: Working with clients in person

When working on a bigger project, the easiest way to improve your work relation with a client or an external product manager, is to make sure you see them in person once in a while.

It makes sense to meet each other when you start working together to establish a relationship and find out what makes them tick.

If you need to discuss a larger package of work, use the opportunity and meet up and discuss it in person.

When you have to discuss something in your daily work, prefer talking to writing, and consider using a webcam.

Pitfall: has_defaults on virtual attributes are nil when loaded from database, of course …

It smells. Rethink your code design.

Code example with makandra/has_defaults:

class Post < ActiveRecord::Base

  has_defaults tags: []          # field in db
  has_defaults virtual_tags: []  # no db field
  
  def all_tags
    virtual_tags + tags
  end
  
end

> Post.new.virtual_tags
=> []   # ✔

> Post.find(1).virtual_tags
=> nil   # ☹

> Post.find(1).all_tags
=> Error: undefined method '+' for nil:NilClass

Flash-Free Clipboard for the Web

Unfortunately, Web APIs haven’t provided the functionality to copy text to the clipboard through JavaScript, which is why visiting GitHub with Flash disabled shows an ugly grey box where the button is supposed to be. Fortunately, we have a solution. The editor APIs provide document.execCommand as an entry point for executing editor commands. The "copy" and cut" commands have previously been disabled for web pages, but with Firefox 41, which is currently in Beta, and slated to move to release in mid-September, it is becoming available to Ja...

An auto-mapper for ARIA labels and BEM classes in Cucumber selectors

Spreewald comes with a selector_for helper that matches an English term like the user's profile into a CSS selector. This is useful for steps that refer to a particular section of the page, like the following:

Then I should see "Bruce" within the user's profile
                                 ^^^^^^^^^^^^^^^^^^

If you're too lazy to manually translate English to a CSS selector by adding a line to features/env/selectors.rb, we already have an [auto-mapper to translate English into ...

AWS Public IP Address Ranges Now Available in JSON Form

I am happy to announce that this information is now available in JSON form at https://ip-ranges.amazonaws.com/ip-ranges.json. The information in this file is generated from our internal system-of-record and is authoritative. You can expect it to change several times per week and should poll accordingly.

postgresql create extension without giving the application superuser rights

If you need a postgresql extension for your database it isn't a good idea to give your applications database user superuser rights (like many people on stackoverflow think)

Just login to the database with a superuser account (e.g. postgres) and create the extension with it.

Example:

# with the default configuration of postgresql you normally can login as `postgres` user
# without a password if you use the systems `postgres` user
$ sudo su -l postgres
$ pgsql
postgres=# \c your_database;
psql (9.3.9, server 9.3.5)
You are now connected...

ActiveRecord: scoped `validates_uniqueness_of` allows one null value per scope

As you most likely know validates_uniqness_of :foreign_id does not allow nil values by default.

To allow nil one has to set the :allow_nil => true option.

Very unexpected scoping this validation will not raise an error if foreign_id set to nil for the first created record of this kind.

validates_uniqueness_of :foreign_id, :scope => :another_column # allows foreign_id to be nil

Without a validation for presence of foreign_id now unusual records could be created.

How to deal with 'parent id missing' error in nested forms

tl;dr

  • Use form models to handle this problem
  • Or soften the validation to validates_presence_of :parent

Usually you would validate presence of parent object id, like in this example:

class Parent < ActiveRecord::Base
  has_many :nested, :inverse_of => :parent
  accepts_nested_attributes_for :nested
end

class Nested < ActiveRecord::Base
  belongs_to :parent
  validates_presence_of :parent_id # <- 
end

With the parent already persisted creating nesteds still works fine.

But one will encounter a *'parent id missing' er...

How to enable SSL in development with Passenger standalone

Here is how to start your Rails application to accept both HTTP and HTTPS in development.

  1. gem install passenger

  2. Create a self-signed SSL certificate. Store the generated files in config/passenger-standalone-ssl.

  3. Create a Passengerfile.json at the project root with this content (or save the attached file):

    {
      "ssl": true,
      "ssl_port": 3001,
      "ssl_certificate": "config/passenger-standalone-ssl/server.crt",
    

    ...

Getting Sidekiq error "delay is defined by Active Record"

Reason: You very likely have a model that has a delay attribute.

You can configure Sidekiq to remove its delay method by adding this to your Sidekiq initializer:

Sidekiq.remove_delay!

If you need to keep Sidekiqs delay features, add Sidekiq.hook_rails! before the option above. The sidekiq methods will be prefixed with sidekiq_ then.

PostgreSQL: Be careful when creating records with specific ids

In tests, it is sometimes useful to create records with specific ids. On PostgreSQL this can cause problems:

Usually, PostgreSQL uses an "autoincrement" sequences to provide sequential ids for new database rows. However, these sequences will not increment if you insert a record "by hand". This will cause an error:

record = Record.create!
record.id                             # => 100, next automatic id will be 101
Record.create!(id: record.id + 1)     # okay, but next automatic id will still be 101
Record.create!                       ...

Mocking time in Jasmine specs

The easiest way to freeze or travel through time in a Jasmine spec is to use the built-in jasmine.clock().

  • After jasmine.clock().install() you can use it to control setTimeout and setInterval.
  • Using jasmine.clock().mockDate() you can mock new Date() (which returns the current time in Javascript)

While you can use SinonJS Fake timers, using the built-in Jasmine clock will save you an extra dependency.

Detecting N+1 queries with Bullet

The Bullet gem is designed to help you increase your application's
performance by reducing the number of queries it makes. It will watch
your queries while you develop your application and notify you when
you should add eager loading (N+1 queries), when you're using eager
loading that isn't necessary and when you should use counter cache.