Bash: Heavy headings for CLI
To print a colored full-width bar on the bash, use this bash script expression:
echo -e '\033[37;44m\nHEADING\033[0m\nLorem ipsum ...'
In Ruby:
puts "\033[37;44m\n #{text}\033[0m" # blue bar
Notes: -e
turns on escape character interpretation for echo
. See this card for details on bash formatting.
The line above will print:
How to load only a subset of a massive MySQL dump
I had a huge MySQL dump that took forever (as in: days) to import, while I actually just wanted to have the full database structure with some data to use on my development machine.
After trying several suggestions on how to speed up slow MySQL dump imports (which did not result in any significant improvement), I chose to import just some rows per table to suffice my needs. Since editing the file was not an option, I used a short Ruby script to manage that.
Here is how:
pv huge.dump | ruby -e 'ARGF.each_line { |l| m = l.match(/^INSERT ...
Ruby constant lookup: The good, the bad and the ugly
In Ruby, classes and modules are called constants. This card explains how Ruby resolves the meaning of a constant.
The good
E. g. in the following example, Array
could mean either Foo::Array
or simply Array
:
class Foo
def list
Array.new
end
end
What Ruby does here is to see if the name Array
makes sense inside of Foo::
, and if that fails, resolves it to ::Array
(without a namespace).
The bad
This is relevant for old Ruby versions. Ruby 2.5+ removes top-level constant lookup whi...
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:
- Expand External Links For Print
- Print QR Codes For Easy URL References
- Use CSS filters to improve the result of printed graphics (i.e. images with transparent parts)
- Use your DevTools to preview the print styles in your browser
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.
- Install pipe viewer, if you don't have it already:
sudo apt-get install pv
- Know the location of the dump file on the remote server. We'll use
/mnt/dumps/my_project.dump.bz2
in the example below. - 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.
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: Change 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');
......