Carrierwave: Auto-rotate tagged JPEGs

Modern cameras often produce JPEGs that have a "I should be rotated 90° to the left" flag. If you process such pictures using Carrierwave this will be ignored and you'll end up with a wrongly rotated image.

Fortunately, this is easy to fix:

In your Uploader, add

process :auto_orient # this should go before all other "process" steps

def auto_orient
  manipulate! do |image|
    image.tap(&:auto_orient)
  end
end

Note: You can add the process :auto_orient outside of all your version blocks and it will apply...

Taming icon fonts for use in Rails views

Icon fonts like Font Awesome are infinitely scalable, look great on high-DPI displays and will give your app a modern look.

However, icon fonts can be very awkward to use compared to raster icons. Elements are given icons by giving them a special class like icon-plus or icon-home:

<span class="icon-plus">Create</span>

The icon font's stylesheet will then recognize this class and insert the icon as the element's :before style.

In practice, this pattern will give you a lot of hea...

CSS: Emulate linear gradients with inset box shadows

Why is this useful?

  • You can have a background image on the same element, overlaying it with a transparent gradient.
  • Since you are probably using gradients to give an element a glossy or three-dimensional feel, box shadows work much better for this. This is because linear gradients always stretch to the full size of the element (which can grow with user input), while a natural shine or shadow only highlights a fixed size on the top or bottom.
  • Browser support for linear gradients is a mess. I avoid using them. In part...

How to not leave trailing whitespace (using your editor or Git)

There is no reason to leave trailing whitespace characters in your project's files, so don't add any.

A git diff --check will tell you if there are any and you should not commit when you see them. So go ahead and switch your editor/IDE to automatically remove them for you.
Below are a few instructions on how to get them removed by your favorite IDE or editor.

Note that except for RubyMine, the following changes will remove trailing white-space on all lines, not only those that you changed.
While this should not be a problem if your proje...

Paperclip: undefined method `to_file' for #<Paperclip::Attachment:0000> (NoMethodError)

to_file has been removed in Paperclip 3.0.1.

Instead of using File to access Paperclip storage objects (like this: File.read(file.to_file.path)) you can use

Paperclip.io_adapters.for(file).read

`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 calls sanitize on each of the generated paragraphs.

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", "acrony...

Distribute files from a private bucket on AWS S3

Given you store files on Amazon S3 and you need to stream those files out to people while you don't want them to be able to distribute the content simply by sharing the S3 URL.

You could either mark the bucket as private and fetch the appropriate files from S3 to your application server and stream them to the client finally. While this is possible, I'd recommend to use what AWS calls "Query String Authentication".

If you're using Paperclip you can chose between two sto...

Imagemagick: Batch resize images

Trick: Do not use convert but mogrify:

mogrify -resize 50% *

This overwrites the original image file.

In contrast, convert writes to a different image file. Here is an example if you need this:

cd /path/to/image/directory
for i in `ls -1 *jpg`; do convert -resize 50% $i "thumb_$i"; done

How to make your application assets cachable in Rails

Note: Modern Rails has two build pipelines, the asset pipeline (or "Sprockets") and Webpacker. The principles below apply for both, but the examples shown are for Sprockets.


Every page in your application uses many assets, such as images, javascripts and stylesheets. Without your intervention, the browser will request these assets again and again on every request. There is no magic in Rails that gives you automatic caching for assets. In fact, if you haven't been paying attention to this, your application is probabl...

Paperclip: Move attachements from local storage to AWS S3

We frequently use the handy Paperclip Gem to manage file attachments.

If you need to move the files from local storage (i.e., your servers' harddisk) to Amazon S3, you can simply change settings for Paperclip to use the S3 storage adapter and use this script to migrate to S3. Put the snippet into a chore if you don't want to run that in the console.
YOUR_LOCAL_STORAGE_MODEL_DIRECTORY should be something like 'storage/your_model'.

Dir.glob(YOUR_LOCAL_STORAGE_MODEL_DIRECTORY**/*).each do |path|...

Beware of magic adblocker rules

If a customer calls and tells you that she cannot see some content of her website beware of the following before starting tcpdump or other forensic debugging tools.

Some ad blockers like Adblock are shipped with filters that remove (amongst others)

  • divs named 'sponsor'
  • images with a class "banner" or the filename "banner.png"
  • images from directories named 'sponsor*'
  • Image names or class names that begin with adv_....

Renaming the div to something more specific to your site and renaming...

How to test print stylesheets with Cucumber and Capybara

A print stylesheet is easy to create. Choose a font suited for paper, hide some elements, done. Unfortunately print stylesheets often break as the application is developed further, because they are quickly forgotten and nobody bothers to check if their change breaks the print stylesheet.

This card describes how to write a simple Cucumber feature that tests some aspects of a print stylesheets. This way, the requirement of having a print stylesheet is manifested in your tests and cannot be inadvertedly removed from the code. Note that you can...

Be careful when using Unicode symbols for graphical elements

There are many fun Unicode characters like ▲ or ☯. You might be tempted to use them for graphical elements in lieu for an image. After all they are so much easier to style and scale than a raster image!

Unfortunately you will discover that these symbols render very differently on Linux, Windows and MacOS. The reason for this is that the font you are using will probably not contain any characters outside the standard Latin-1 set. When browsers encounter a character not included in the current font, they use a fallback font for this one cha...

How to fix: Firefox uses incorrect fonts on all webpages, regardless of their CSS

If you encounter a Firefox that does not care about your font settings but always uses specific fonts, you can fix that. Usually this should not happen, as it's not a default setting:

  1. Open up the Preferences.
  2. Switch to "Content".
  3. In the "Fonts & Colors" section, click the "Advanced..." button.
  4. Tick "Allow pages to choose their own fonts, instead of my selection above".
  5. Confirm by pressing "OK".

![Screenshot](https://makandracards.com/makandra/10913-how-to-fix-firefox-uses-incorrect-fonts-on-all-webpages-regardless-of-their-c...

LibreOffice won't embed most fonts into PDFs (with fix)

  • LibreOffice Impress, Writer, etc. doesn't embed most fonts into the PDFs it generates.
  • This means if you share a slide show with a font that is not Arial or Times, other people will get an error message "Cannot extract the embedded font 'XYZ Some characters may not display or print correctly" and unreadable text. Everybody loses.
  • Some forums will recommend that you tick "PDF/A-1a" in the PDF options to make LibreOffice embed fonts. In reality, thi...

Rails asset pipeline: Why relative paths can work in development, but break in production

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 pipeline, you can use the full power of Ruby to generate assets. E.g. you can have ERB tags in your Javascript. Or you can have an ERB template which generates Haml which generates HTML. You can chain as many preprocessors as you want.

When you deploy, Rails runs assets:precompile...

Mysterious "margin" below an image

Consider the following HTML & CSS:

<div><img src='http://makandra.com/images/makandra-ruby-on-rails.png' /></div>

^
img {
background-color: red;
}
div {
border: 1px solid black;
}

This will leave a margin of about 5px between the lower edge of the image and the containing div, although there are no paddings or margins set, and there's no whitespace. The reason is, the image will vertically align baseline, and the space below the image is just kept for descenders (the part of letters below the basel...

Gimp: Why removing pixels sometimes leaves transparency, sometimes the background color

  • You might have notices this behavior when you cut a selection or use the rubber tool.
  • The behavior depends on whether your images has an alpha channel.
  • You can add an alpha channel by choosing Layer → Transparency → Add alpha channel

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

Compress bitmap images within PDF files

Embedding bitmap images within PDF sometimes results in large files because the bitmaps are not compressed. If you don't need high quality images within the resulting PDF file, you can use ghostscript to compress embedded images:

ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=new-smaller-file.pdf large-original-file.pdf

Note that your PDF printer (or similiar generation tools) also often come with a compression setting for embedded raster images.

You can put this ...

Howto properly use vertical-align to align elements vertically

Say you want to vertically align a div box inside a div container. This is how you do it:

HTML

<div id="container">
  <div class="box">
    <span> Some text...<br />in two lines. </span>
  </div>
</div>

CSS

Set the line-height to the container's (implicit) height. The container MUST have a height >= its line-height, because the line-height actually spans the area inside which .box will align vertically.

#container {
  line-height: 50px;
}

Because the container's line-height is inherited by .box,...