PSA: Umlauts are not always what they seem to be

When you have a string containing umlauts which don't behave as expected (are not matched with a regexp, can't be found with an SQL query, do not print correctly on LaTeX documents, etc), you may be encountering umlauts which are not actually umlaut characters.

They look, depending on the font, like their "real" umlaut counterpart:

  • ä ↔ ä
  • ö ↔ ö
  • ü ↔ ü

However, they are not the same:

'ä' == 'ä' # false
'ä'.size # 1
'ä'.size # 2

Looking at how those strings are constructed reveals what is going on:

'ä'.unpack('U*...

Removing MiniTest warnings from Rails 4 projects

Warnings like those below may originate from rspec or shoulda-matchers or other gems that have not updated yet to the new MiniTest API.

One

Warning: you should require 'minitest/autorun' instead.
Warning: or add 'gem "minitest"' before 'require "minitest/autorun"'
# (backtrace)

Solution: Add gem 'minitest' to your Gemfile, before any rspec gem.

Another

MiniTest::Unit::TestCase is now Minitest::Test. From /Users/makandra/.rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/tes...

A Ruby script that installs all gems it is missing

So you want your Ruby script to install missing gems instead of dying? Take this method:

def installing_missing_gems(&block)
  yield
rescue LoadError => e
  gem_name = e.message.split('--').last.strip
  install_command = 'gem install ' + gem_name
  
  # install missing gem
  puts 'Probably missing gem: ' + gem_name
  print 'Auto-install it? [yN] '
  gets.strip =~ /y/i or exit(1)
  system(install_command) or exit(1)
  
  # retry
  Gem.clear_paths
  puts 'Trying again ...'
  require gem_name
  retry
end

Use it like this:

insta...

YAML: Keys like "yes" or "no" evaluate to true and false

If you parse this Yaml ...

yes: 'Totally'
no: 'Nope'

... you get this Ruby hash:

{ true: 'Totally',
  false: 'Nope' }

In order to use the strings 'yes' and 'no' as keys, you need to wrap them with quotes:

'yes': 'Totally'
'no': 'Nope'

There's actually a long list of reserved words with this behavior:

y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF

I'm sorry.

Bash output redirection

There are 3 built-in file descriptors: stdin, stdout and stderr (std=standard). (You can define your own, see the linked article.)

Basic

  • 0/1/2 references stdin/stdout/stderr
  • >/2> redirects stdout/stderr, where > is taken as 1>
  • &1/&2 references stdout/stderr
  • &> redirects stdout and stderr = everything (caution: see below)

Caution: &> is functional as of Bash 4. This seems to result in a slightly differing behaviour when redirecting output in Ru...

Persist Rails or IRB Console Command History After Exit

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

require 'irb/ext/eval_history' # was 'irb/ext/save-history' for versions prior to Ruby 3.3
IRB.conf[:SAVE_HISTORY] = 2000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"

Strong params: Raise in development if unpermitted params are found

Rails 4:

config.action_controller.action_on_unpermitted_parameters enables logging or raising an exception if parameters that are not explicitly permitted are found. Set to :log or :raise to enable. The default value is :log in development and test environments, and false in all other environments.

Rails 3:

If you include the strong_params gem, see the Readme for handling unpermitted keys.

Mute Rails asset pipeline log messages

quiet_assets helps with disabling asset pipeline log messages in the development log. When the gem is added, asset pipeline logs are suppressed by default.

If you want to disable muting temporarily, add config.quiet_assets = false to your config/application.rb.

Disabling Spring when debugging

Spring is a Rails application preloader. When debugging e.g. the rails gem, you'll be wondering why your raise, puts or debugger debugging statements have no effect. That's because Spring preloads and caches your application once and all consecutive calls to it will not see any changes in your debugged gem.

Howto

Disable spring with export DISABLE_SPRING=1 in your terminal. That will keep Spring at bay in that terminal session.

In Ruby, [you can only write environment variables that subproc...

How to create Rails Generators (Rails 3 and above)

General

Programatically invoke Rails generators

Require the generator, instantiate it and invoke it (because generators are Thor::Groups, you need to invoke them with invoke_all). Example:

 require 'generators/wheelie/haml/haml_generator'
 Generators::HamlGenerator.new('argument').invoke_all

Other ways: Rails invokes its generators with Rails::Generators.invoke ARGV.shift, ARGV. From inside a Rails generator, you may call the [inherited Thor method invoke(args=[], options={}, config={})](https://github...

docopt: A promising command line parser for (m)any language

docopt helps you define interface for your command-line app, and automatically generate parser for it.

docopt is based on conventions that are used for decades in help messages and man pages for program interface description. Interface description in docopt is such a help message, but formalized. Here is an example:

Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h |...

Remove Rubygems deprecation warnings

Rubygems can produce lots of deprecation warnings, but sometimes, you cannot fix them. To have a tidy terminal with output that matters, add this to the top of your Gemfile and enjoy silence:

Deprecate.skip = true if defined?(Deprecate.skip)
Gem::Deprecate.skip = true if defined?(Gem::Deprecate.skip)

# all gems go here ...

(Inspiration)

Hash any Ruby object into an RGB color

If you want to label things with a color but don't actually care which cholor, you can use the attached Colorizer class.

To get a completely random color (some of which will clash with your design):

Colorizer.colorize(some_object) # => "#bb4faa"

To get similiar colors (e. g. bright, pale colors of different hues):

 # random hue, saturation of 0.5, lightness of 0.6
Colorizer.colorize_similarly(some_object, 0.5, 0.6) # => "#bbaaaa"

Also see the color gem.

Debugging AJAX requests with better_errors

better_errors is an awesome gem for enhanced error pages in development, featuring a live-REPL for some light debugging.

To debug the exception you got on an AJAX-Request, visit /__better_errors on your app's root path (e.g. http://localhost:3000/__better_errors). It shows the error page for the last exception that occurred, even when it has been triggered by an AJAX request.

Ruby: How to camelize a string with a lower-case first letter

If you want to do JavaScript-style camelization, ActiveSupport's String#camelize method can actually help you out. Simply pass a :lower argument to it.

>> 'foo_bar_baz'.camelize
=> "FooBarBaz"
>> 'foo_bar_baz'.camelize(:lower)
=> "fooBarBaz"

No more file type confusion in TextMate2

When using TextMate2 with the cucumber bundle, it does not recognize step definitions (e.g. custom_steps.rb) as such but believes they are plain Ruby files. But there is help!

Solution

Add these lines to the bottom of your .tm_properties file (in ~/ for global settings, in any directory for per-project settings):

[ "*_steps.rb" ]
fileType = "source.ruby.rspec.cucumber.steps"

Apparently, this works for any files. Define a regex and specify custom settings. The attached article lists all available configuration options (whic...

Why Ruby Class Methods Resist Refactoring

In a nutshell:

  • Splitting a long method into sub methods is easier in instances since it is in classes. Since you must not save state in a class, you need to pass around context as a long chain of parameters again and again.
  • If your public API has a single entry point, you can still have a class-level method that takes care of constructing the instance etc. So it's all win.

Thread Safety With Ruby — Luca Guidi

Ruby’s model for concurrency is based on threads. It was typical approach for object oriented languages, designed in the 90s. A thread is sequence of instructions that can be scheduled and executed in the context of a process. Several threads can be running at the same time.

Ruby’s VM process allocates a memory heap, which is shared and writable by threads. If incorrectly coordinated, those threads can lead to unexpected behaviors.

Ruby on Rails 4 and Batman.js

Batman is an alternative Javascript MVC with a similar flavor as AngularJS, but a lot less features and geared towards Ruby on Rails.

The attached link leads to a tutorial for a small blog written with Rails / Batman.js.

I'm collecting other Batman.js resources in my bookmarks.

How Ruby method lookup works

When you call a method on an object, Ruby looks for the implementation of that method. It looks in the following places and uses the first implementation it finds:

  1. Methods from the object's singleton class (an unnamed class that only exists for that object)
  2. Methods from prepended modules (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its an...

Collection of Rails development boosting frameworks

Development environment setup

Rails Composer

Basically a comprehensive Rails Template. Prepares your development environment and lets you select web server, template engine, unit and integration testing frameworks and more.

Generate an app in minutes using an application template. With all the options you want!

Code generators

Rails Bricks

A command line wizard. Once you get it running, it creates sleek applications.

RailsBricks enables you to cre...

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: