View

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…

Repeats

How to create giant memory leaks in AngularJS

This guide shows how to create an AngularJS application that consumes more and more memory until, eventually, the browser process crashes on your users.

Although this guide has been written for Angular 1 originally, most of the advice is relevant for all client-side JavaScript code.

How to observe memory consumption

To inspect the amount of memory consumed by your Javascripts in Chrome:

  • Open an incognito window
  • Open the page you want to inspect
  • Press Shift + ESC to see a list of Chrome processes…
Auto-destruct in 57 days

Updated: Upgrading a Rails app to Cucumber 3

The official cucumber-rails 1.6.0 gem is now compatible with Cucumber 3. If your Gemfile fetches cucumber-rails from the repo's master, you can now switch it back to RubyGems.

Repeats

AJAX requests with PATCH or DELETE method will not redirect with GET

Redirect responses to PATCH and DELETE requests will be followed with PATCH or DELETE. Redirect responses to GET and POST will be followed with a GET.
The Rails form_for helper will use a workaround to send POST requests with a _method param to avoid this issue for PATCH/DELETE.

If you make requests yourself, watch out for the following behavior.

When you make an AJAX request PATCH /foo and the /foo action redirects to /bar, browsers will request PATCH /bar. You probably expected the second request to be…

Repeats

Don't compare datetimes with date ranges in MySQL

When selecting records in a date range, take care not to do it like this:

start_date = Date.parse('2007-05-01')
end_date = Date.parse('2007-05-31')
LogItem.where(:created_at => start_date .. end_date)

The problem is that created_at is a datetime (or Time in Ruby), while start_date and end_date are simple dates. In order to make sense of your query, MySQL will cast your dates to datetimes where the time component is 00:00:00. Because of this the query above will lose records created from 2007-05-31 00:00:01 t…

Repeats

Webpacker: Configuring browser compatibility

Webpacker uses Babel and Webpack to transpile modern JavaScript down to EcmaScript 5. Depending on what browser a project needs to support, the final Webpack output needs to be different. E.g. when we need to support IE11 we can rely on fewer JavaScript features. Hence our our output will be more verbose than when we only need support modern browsers.

Rails 5.1+ projects often use Webpacker to preconfigure the Webpack pipeline for us. The default configuration works something like this:

  1. Webpack chec…

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 …

Repeats

Testing the spam score of an email

This site gives you some hints, how you can improve the overall rate of successful deliveries. The analyse covers both the email formatting and the server configuration.

spam-score.jpg

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    ...
Repeats

Fix PNG colors in IE, old Safaris and new Firefoxes

Some browsers render PNG images with color profiles and other shenanigans, some don't. Remove some PNG chunks to render colors uniformly.

Geordi brings a command png-optimize which conveniently optimizes your PNGs for the web. See Github for a description

  • Single file and batch optimization is supported
  • png-optimize will overwrite the original files

Without Geordi

Linux:
sudo apt-get install pngcrush
  • Single file:

    pngcrush -rem...
    
External content

Persist Rails or IRB Console Command History After Exit

Create, or edit your ~/.irbrc file to include:

require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 2000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"
Auto-destruct in 45 days

Geordi 1.9.1 released

0c6de4e Make :show_cmd prettier
f56973e Improve security-update workflow
2a55ef1 Make security-update compatible with Capistrano 3
bacd12f sort list of dumps
Repeats

Rails asset pipeline: Why things break in production and what precompilation does to your assets

When you work with a Rails 3.1+ application, you will be working with the asset pipeline. The asset pipeline is awesome until you deploy. Then it will be less so if you haven't done everything as the pipeline expected it from you.

The problem

When using the asset pipeline your assets (images, javascripts, stylesheets, fonts) live in folders inside app:

app/assets/fonts
app/assets/images
app/assets/javascripts
app/assets/stylesheets

With the asset p…

ActionMailer: send mail from console

If your rails application is unable to send mails, it might be useful to debug your settings using the rails console. Here is a snippet that shows the current settings and lets you send a test mail directly from the console:

m = ActionMailer::Base.new
m.delivery_method # -> :smtp
m.smtp_settings
m.mail(from: 'sender@example.com', to: 'recipient@example.com', subject: 'test') do |format|
  format.text { m.render plain: "Hello, you've got mail!" }
end.deliver

Repeats

Use find_in_batches or find_each to deal with many records efficiently

Occasionally you need to do something directly on the server – like having all records recalculate something that cannot be done in a migration because it takes a long time.

Let's say you do something like this:

Project.all.each(&:recalculate_statistics!)

Even though you may have been successful with this on your development machine or the staging server, keep in mind that production machines often hold a lot more records. Using all may just work, even with lots of records, but when you iterate over such records and fetch associati…

PostgreSQL: How to show table sizes

When you have a large PG database, you may want to find out which tables are consuming the most disk space.
You can easily check this using the following SQL statement from the PostgreSQL wiki.

SELECT nspname || '.' || relname AS "relation",
    pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
  FROM pg_class C
  LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
  WHERE nspname NOT IN ('pg_catalog', 'information_schema')
    AND C.relkind <> 'i'
    AND nspname !~ '^pg_toast'
  ORDER BY pg_tot...
Repeats

simple_format does not escape HTML tags

simple_format ignores Rails' XSS protection. Even when called with an unsafe string, HTML characters will not be escaped or stripped!

Instead simple_format has a whitelist of tags it allows. These are:

ActionView::Base.sanitized_allowed_tags
=> #<Set: {"small", "dfn", "sup", "sub", "pre", "blockquote", "ins", "ul", "var", "samp", "del", "h6", "h5", "h4", "h3", "h2", "h1", "span", "br", "hr", "em", "address", "img", "kbd", "tt", "a", "acronym", "ab...
Auto-destruct in 40 days

Updated: How to change the hostname in Cucumber features

Updated example step for Capybara > 2.14. New usage:

page.config.stub app_host: "http://#{host}"
View
3463 cards