Bash: How to only do things in interactive shells

When you print something from within your .bashrc file you will run into trouble when copying something onto your machine using scp for example.

This is because the output from your .bashrc interferes with scp. The solution is to decide whether the bash shell is started interactively (you start a terminal on your screen) or not (scp).

if [ ! -z "$PS1" ]; then
  # This happens in interactive shells only and does not interfere with scp.
  echo "Learn!"
fi

Howto provide a single page preview for PDF & TXT with carrierwave

Assert rmagick provision ...

Gemfile

gem 'rmagick', '2.13.2' # at this moment the latest stable version

config/initializer/carrierwave.rb

require 'carrierwave/processing/rmagick'

... and define a custom processor

MyUploader.rb

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  def cover
    manipulate! do |frame, index|
      frame if index.zero? # take only the first page of the file
    end
  end

  version :preview do
    process :cover
    process :resize_to_fit => [310,...

Don't use PDFKit v0.5.4 – it breaks on dead urls

When I upgraded from 0.5.4 PDFKit deadlocked or crashed when an ApplicationController::RouteError occured. If this error happens only because of a broken image link you probably still wan't the page to render and get a PDF with a "missing image placeholder" instead.

I don't know yet in which version (0.5.2, 0.5.3 or 0.5.4) the bug was built in. At the moment I'm doing fine with 0.5.1 and I didn't evaluate any other versions yet.

I will update this card as soon as I know further information (State 4th Nov. 2013).

Fix „command failed: /usr/bin/wkhtmltopdf ...“ using PDFKit middleware

Ubuntu 12.04 LTS x64, Ruby 1.8.7, Rails 2.13, PDFKit 0.5.4, Phusion Passenger Apache 2

I ran into this, when I started using passenger to deal with the Single Thread Issue which caused my webrick to deadlock when an ActionController::RoutingError (No route matches "...") occurred.

These steps brought me a little further

(1) assert dependencies are installed

 sudo aptitude install openssl build-essential xorg libssl-dev

(2) only for 64bits OS Run one by one the follo...

Implementing social media "like" buttons: Everything you never wanted to know

So you client has asked you to implement a row of buttons to like the URL on Facebook, Twitter and Google+. Here are some things you should know about this.

0. Security considerations

Each "like" button is implemented by including a Javascript on your site. This means you are running fucking remote code on your page. You are giving Facebook, Twitter and Google+ full permission to e. g. copy user cookies. Check with your client if she is cool with that. Also note that if you're site is suggesting security by operating under HTTPS ...

PostgreSQL cheat sheet for MySQL lamers

So you're switching to PostgreSQL from MySQL? Here is some help...

General hints on PostgreSQL

  • \? opens the command overview
  • \d lists things: \du lists users, \dt lists tables etc

Command comparison

Description MySQL command PostgreSQL equivalent
Connect to the database mysql -u $USERNAME -p sudo -u postgres psql
Show databases SHOW DATABASES; \l[ist]
Use/Connect to a database named 'some_database' USE some_database; \c some_dat...

Rails: Output helpers for migrations

When you're writing migrations that do more than changing tables (like, modify many records) you may want some output. In Rails > 3.1 you have two methods at hand: announce and say_with_time.

In the migration:

class AddUserToken < ActiveRecord::Migration

  class User < ActiveRecod::Base; end

  def up
    add_column :users, :token, :string
    
    announce "now generating tokens"
    User.find_in_batches do |users|
      say_with_time "For users ##{users.first.id} to ##{users.last.id}" do
        users.each do |user|
        ...

Render a view from a model in Rails

In Rails 5 you can say:

ApplicationController.render(
  :template => 'users/index',
  :layout => 'my_layout',
  :assigns => { users: @users }
)

If a Request Environment is needed you can set attributes default attributes or initialize a new renderer in an explicit way (e.g. if you want to use users_url in the template):

ApplicationController.renderer.defaults # =>
{
  http_host: 'example.org',
  https:      false,
  ...
}
...

How to inspect XML files in a terminal

You can use xmllint to pretty-print ugly XML files on your terminal. Just say:

xmllint --format file.xml

That will restructure containers nicely into individual sections with proper indentation.\
Note that it will automagically work on gzipped XML files!

To write pretty output to a new file, just use the -o switch (short for --output):

xmllint --format file.xml -o pretty_file.xml

See the xmllint man page for other useful switches and more information.

Tips And Tricks For Print Style Sheets

Smashing Magazine lists some handy tricks for print style sheets, all with CSS:

Loading dumps via SSH, unpacking and sourcing them, all with a progress bar

Here is a hacky way to load dumps directly from the source server, without fully copying them over and extracting them first.

It may break horribly for you. This is the dark side of the force.

  1. Install pipe viewer, if you don't have it already: sudo apt-get install pv
  2. Know the location of the dump file on the remote server. We'll use /mnt/dumps/my_project.dump.bz2 in the example below.
  3. Find out the size of the (bzipped) file in by...

Firefox introduces PDF viewer

Prepare to explain customers what changed if your application renders PDF documents to users.

Xfce: Take a screenshot with the "Print" key

  • Go to Settings Manager / Keyboard / Application Shortcuts
  • Add a shortcut for the Print key that calls xfce4-screenshooter -f

This may be configured for you by default.

Literally 101 Ruby tricks

The linked slidedeck holds many tips, of which I list the most interesting to me below

DATA and END

The __END__ keyword tells Ruby where a file ends – but you don't have to stop there. Any text you add after it is accessible via the DATA object.

Running the attached example file data.rb prints:

DATA is a File object to everything in the current file after "__END__"

No braces needed for 'special variables'

@instance, @@class, $global = [ 'instance', 'class', 'global' ]
puts "#@instance, #@@class, #$global"

...

How Ruby lets you keep script and data in *one* file

The __END__ keyword tells Ruby where a file ends – but you don't have to stop there. Any text you add after it is accessible via the DATA object.

The attached example file data.rb looks like this:

puts DATA.read

__END__
DATA is a File object to everything in the current file after "__END__"

Running it with ruby data.rb prints:

DATA is a File object to everything in the current file after "__END__"

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

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

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

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

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

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');

......

Inspecting a live Ruby process

How to get a backtrace from a running Ruby process:

Ruby 2.6

# First, find out the PID of your Ruby process (e.g. passenger-status)
$ sudo gdb -p PID
(gdb) call rb_eval_string("$stderr.reopen('/tmp/ruby-debug.' + Process.pid.to_s); $stderr.sync = true") # redirects stderr
(gdb) call rb_backtrace() # prints current backtrace to /tmp/ruby-debug.xxx

Stop the process afterwards, since stderr is now borked.

It is possible you have to call rb_backtrace() multiple times to get the full stacktrace.

Previous method on Ruby 2....

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