Virtus can coerce structured values

Just a quick note that Virtus can coerce (auto-cast) structured values like collections or maps:

class Klass
  include Virtus.model

  attribute :dimensions, Hash[Symbol => Float]
  attribute :numbers, Array[Integer]
end

Check out the Virtus README, it's full of nice things like this!

Careful when calling a Ruby block with an array

When a Ruby block or proc takes multiple parameters, and you call it with an Array, Ruby will unexpectedly splat the array elements:

block = proc { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # "a=1, b=2"

Note that lambdas behave as expected:

block = lambda { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # ArgumentError: wrong number of arguments (1 for 2)

Embed Font Awesome icons from your CSS

An annoying part of using font icons is that the icons usually need to live in the DOM. This is a step back from the time when we defined raster icons with background-image, in the CSS.

It doesn't have to be that way.

Copy the attached file font-awesome-sass.css.sass to your assets (we recommend /vendor/asset-libs/font-awesome-sass).

You can now use Font Awesome icons from your Sass files:

@import font-awesome-sass

...

CarrierWave: Don't use #url when you mean a file path

CarrierWave attachments have two distinct methods #url and #path which appear to behave the same:

document.file.url   # => /storage/documents/4/letter.doc
document.file.path  # => /storage/documents/4/letter.doc

However, starting with CarrierWave 0.9, #url will properly escape high-ASCII characters:

document.file.url   # => /storage/documents/4/h%C3%BCte.doc
document.file.path  # => /storage/documents/4/hüte.doc

So always use #url if you mean an actual URL (e.g. to display an <img>). But use #path if y...

Build cronjobs or list next dates

"CronMaker is a utility which helps you to build cron expressions." Check it out at http://www.cronmaker.com/.

To simply check syntax of a cron schedule, paste it into your personal crontab file using crontab -e. If you have syntax errors, the crontab command will complain like this:

crontab: installing new crontab
"/tmp/crontab.3szkFA/crontab":0: bad minute
errors in crontab file, can't install.
Do you want to retry the same edit? (y/n) y

Ruby: How to measure code execution time in an IRB or Rails console

Modern IRB has time measurement built in.

measure # Enable
measure :off # Disable

Custom

Should your version of IRB not offer this feature, you can measure manually. Paste this method into your console:

def time(&block) puts Benchmark.measure(&block) end

Now time { Some.lengthy_task } will behave similar to the bash time command. Of course you can do much more with the Benchmark object than just putsing it – adapt to your needs.

Use the Ruby debugger on Rails 2 script/runner scripts

This card needs to be updated for Rails 3+.


Since there is no --debugger flag you need to run:

rdebug script/runner lib/scripts/something.rb

That will open an debugging IRB right away, like this:

require File.dirname(__FILE__) + '/../config/boot'
(rdb:1) _

Enter c to continue and reach your actual debugger call. Then, debug away.

If nothing happens for you: Make sure ruby-debug is available in the Gemfile and you require it.

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

How to silence "I18n.enforce_available_locales" deprecation warnings

Before Rails 3.2.14, when supplying an invalid locale to I18n, it would fall back to its config.i18n.default_locale (which is :en by default). Eventually, this will be changed to raise an error by default -- for now, it shows a deprecation warning.

Since Rails 3.2.14 and 3.2.15 did not include security updates, you might not have applied them and probably now encounter these deprecation warnings after upgrading to 3.2.16 (or 4.0.2):

[deprecated] I...

Ruby 1.8: SimpleDelegator is very slow

If you're still working on ruby 1.8, you should know that using SimpleDelegator is often prohibitively slow. I have seen SimpleDelegator.new(myActiveRecordModel) take 50ms+ per instantiation.

The reason is that SimpleDelegator actually loops through all methods of an object and does a define_method. Which is not exactly fast.

To speed up your code, you can often simply replace

class MyUserDecorator < SimpleDelegator
   ...
end

with

class MyUserDecorator < DelegateClass(User)
   ...
end

This...

Spreewald 0.8.0 brings a file attachment step

# Attach a file
#
# Example:
#
#   Company.new.logo = File.new…
#
#   Given the file "…" was attached as logo to the company above
#
#
# Example:
#
#   class Gallery
#     has_many :images, :as => :owner
#   end
#
#   class Image
#     belongs_to :owner, polymorphic: true
#   end
#
#   # so container = Image.new; container.file = File.new… , container.owner = object
#
#   Given the file "…" was attached as Image/file to the company above
#
#
# Example:
#
#   Set updated_at with
#
#     Given … above at "2011-11-11 11:11"
#

Virtual attributes for integer fields

Note that this card is very old. You might want to use ActiveType for your auto-coerced virtual attributes instead.


We sometimes give our models virtual attributes for values that don't need to be stored permanently.

When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that...

howto fix spreewald issue „database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)“

This error occurs when you already have a database.yml which defines the database for the cucumber environment instead of test. (Spreewald database.sample.yml has changed)

Fix

Change cucumber to test in your databse.yml

test:    # <---
  adapter: mysql2
  database: spreewald_test
  encoding: utf8
  host: localhost
  username: root
  password: password

Rubymine >= 5.4.3.2.1 supports keybinding for "Goto next/previous splitter"

Rubymine supports keybinding to switch panes by hotkey like awesome window manager users are used to.

Type "splitter" in the top right keymap section search field (not the global settings search).

Note: A splitter is what you get after using split vertically or split horizontally.

How to find out the type of a model's attribute

When you want to find out the data type of an attribute, you can just use ActiveRecord's columns_hash method.

It returns a hash of column objects that include a type attribute (and more database-related information).

Example:

Contract.columns_hash['id'].type
 => :integer
Contract.columns_hash['active'].type
 => :boolean
Contract.columns_hash['updated_at'].type
 => :datetime

Alan Klement: Replacing The User Story With The Job Story

I've written about the problem with user stories before. At the time, I found it better to just have the team talk over proposed changes to the product. This worked great when the team had gelled and the product is very mature; however, now I'm working with a new team and building a product from scratch. In this case, because our canvas is blank, we are having trouble getting on the same page when it comes to customer motivations, events and expectations. But today, things have turned around. I've come across a great way to use the jobs to...

pickadate.js

The mobile-friendly, responsive, and lightweight jQuery date & time input picker.

Does not depend on jQuery UI, but currently does not allow typing in the associated input field.

An Illustrated Guide to SSH Agent Forwarding

Note - This is not a tutorial on setup or configuration of Secure Shell, but is an overview of technology which underlies this system.

How to subscribe to Ruby security updates

Ruby publishes security issues and MRI updates on ruby-lang.org. Unfortunately there is no straight-forward way to subscribe to these updates via e-mail.

I fixed this for me by taking their RSS feed and submitting it to Blogtrottr. Blogtrottr is an RSS-to-email service that sends you an e-mail whenever the feed updates.

kickstarter/rack-attack

Rack::Attack is a rack middleware to protect your web app from bad clients. It allows whitelisting, blacklisting, throttling, and tracking based on arbitrary properties of the request.

MySQL: How to clone a database

Here is a way to create a duplicate of one database, with all its tables and their data, under a new name.

  1. Make a dump of your source database:

    mysqldump -uroot -p my_project -r my_project.sql
    

    Or, if you only want to dump the database's table structure (schema) without any contents:

    mysqldump -uroot -p my_project -r my_project.sql --no-data
    
  2. Open up a MySQL shell:

    mysql -uroot -p
    
  3. From the MySQL shell, create a new database and populate it with the dumped data:

    CREATE DATABASE my_project_copy;
    

...

Slice a nested hash

The attached initializer gives your hashes a #deep_slice method that lets you recursively slice their contents by a given whitelist of allowed keys and sub-keys:

{ :a => { :b => 'b', :c => 'c' } }.deep_slice(:a => :c) # => { :a => { :c => 'c' } }

ftlabs/fastclick

FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic.