metric_fu: A Ruby Gem for Easy Metric Report Generation

Metric_fu is a set of rake tasks that make it easy to generate metrics reports. It uses Saikuro, Flog, Flay, Rcov, Reek, Roodi, Subversion, Git, and Rails built-in stats task to create a series of reports. It's designed to integrate easily with CruiseControl.rb by placing files in the Custom Build Artifacts folder.

graysky's translator at master - GitHub

Rails extensions to simplify internationalization

sdsykes's read_from_slave at master - GitHub

Read_from_slave for Rails enables database reads from a slave database, while writes continue to go to the master

A/Bingo: RoR Split Testing by Bingo Card Creator

A/Bingo is a Ruby on Rails A/B testing framework written as a plugin.

SecureRandom -- Stop writing your own random number and string generators - Momoro Machine

Stop writing your own random string generators. Rails does this for you.

xing's flag_shih_tzu at master - GitHub

A rails plugin to store a collection of boolean attributes in a single ActiveRecord column as a bit field.

samdanavia's ambitious_query_indexer at master - GitHub

Ambitious Query Indexer is a Rails plugin to identify database indexes that are missing. Rather than looking at tables and guessing what needs indexing, it will locate and run as many queries as it can find and suggest indexes that could be added based upon its findings.

ryanb's trusted-params at master - GitHub

Rails plugin which adds a convenient way to override attr_accessible protection.... You can mark certain attributes as trusted for different roles.

eliotsykes's asset_fingerprint at master - GitHub

Asset Fingerprint Plugin for Ruby on Rails - allows you to use md5 or timestamps in query string or in asset filenames as suggested by Google Page Speed

Declare different CSS background-images for different locales

If you would like to use language specific layout (e.g. background-images) in your applications stylesheets you can achieve this easily by using the lang attribute in your views (ERB):

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<%= I18n.locale || 'en' %>" lang="<%= I18n.locale || 'en'%>">
...
</html>

or in HAML:

%html :xmlns => "http://www.w3.org/1999/xhtml", :"xml:lang" => I18n.locale || 'en', :lang => I18n.locale || 'en'

Then, in your stylesheet you can for example declare different background-images fo...

Start Rails console or server with debugger

When you require the Ruby debugger to be available from your Rails console (e.g. you want to inspect a method's magic), you need to enable it explicitly:
script/console --debugger

If you cannot access local variables etc, see this card.

WEBrick

For WEBrick, enable it similarly:
script/server --debugger

Removing ANSI color codes from Rails logs

The colors in Rails log files are helpful when watching them but, since they are ANSI color codes like ^[[4;36;1m, can be annoying when you are reading the logs with a tool that does just prints those control characters (like less or vim).

Remove them with sed:

cat staging.log | sed -r "s/\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]//g"

This will print the log without colors to your terminal. You can pipe the result into less for example.

To have a file you can vim around with, just write that output into a new file:

ca...

Define an array condition that selects on dynamic columns

For some reason you want to define a find condition in array form. And in that condition both column name and value are coming from user input and need to be sanitized.

Unfortunately this works in SQLite but does not in MySQL:

named_scope :filter, lambda { |attribute, value|
  { :conditions => [ 'articles.? = ?', attribute, value ] }
}

The solution is to use [sanitize_sql_array](http://apidock.com/rails/ActiveRecord/Base/sa...

Cucumber step to pick a datetime in Rails' horrible datetime_select

Please don't use the horrible datetime_select helper. It has a terrible UI. Always prefer to use a visual time picker like Rome instead.

In case everything has failed and you do need a Cucumber step to pick a datetime datetime_select, here it is:

When(/^I select the time (\d+)\-(\d+)\-(\d+) (\d+):(\d+) from "(.*?)"$/) do |year, month, day, hour, minute, label_text|
  label = page.find('label', text: label_text)
  id = label[...

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

Why a Rails flash message is shown twice

You set a flash message and it shows up as it should. However, it is displayed again the next time you follow a link. Here is why:

You have to differentiate between a render and a redirect_to because a flash message is only deleted after a redirect. If you want a message to be seen in the next request after a redirect, use flash[]. If you want a message to be seen in the current request, use flash.now[].

Workaround for the lazy

If you cannot be bothered to decide which flash hash to use, or if the fl...

Rails: How to get PostgreSQL version being used

To check the currently running PG version from your Rails application (e.g. Rails console on your production server), simply do this:

ActiveRecord::Base.connection.select_value('SELECT version()')

How to access your Rails session ID

This only works when you actually have a session ID (not the case for Rails' CookieStore, for example):

request.session_options[:id]
# => "142b17ab075e71f2a2e2543c6ae34b94"

Note that it's a bad idea to expose your session ID, so be careful what you use this for.

Fix error: rails console - no such file to load -- readline

Install libreadline:

sudo apt-get install libreadline-dev

Reinstall the ruby and tell rvm where to find readline

rvm reinstall 1.8.7 --with-readline-dir=/usr/include/readline

Make sure you get a huge cup of tea before running the command above! It will take some time.

References

Capistrano + Rails: Tagging production deploys

Just like Ruby Gems tag their version releases to the corresponding Git commit, it can be helpful to track production deploys within the commit history. This task does the tagging for you.

Capistrano 3

# lib/capistrano/tasks/deploy.rb
namespace :deploy do
  ...

  desc 'Tag the deployed revision'
  task :tag_revision do
    date = Date.today.to_s

    puts `git tag deploy-#{date} #{fetch :current_revision}`
    puts `git push --tags origin`
  end

end
# config/deploy/production.rb
after 'deploy:finished', 'deploy:tag_revi...

Rails 5's ApplicationRecord is the place to put generic model logic

Since Rails 5, domain models inherit from ApplicationRecord by default.

This is the place to put code that should be available in all your application's models.
There is no reason to monkey-patch ActiveRecord::Base when following that practice.

remove_index fails silently for non-existing indexes in Rails 2 migrations

When you try to remove a non-existing index using remove_index, the migration will incorrectly pass without an error. The schema will not be changed, but the migration will be considered migrated.

Since this might be fixed in the future, you cannot mend your database by adding another migration on top of the faulty one. You should manually alter the database schema to the previous migration on all machines that migrated the faulty migration (inform your fellow developers), then delete the faulty migration from the repository.

Caching may break relative paths in your merged stylesheet

If you turn on stylesheet caching, it might happen that stylesheets from different locations with different relative pathes will be put together to one big stylesheet.

This stylesheet then resides in /stylesheets but still holds the old pathes, which aren't valid anymore. This leads to the effect that images are displayed on your local development machine (where caching is turned off automatically) but not on the server.

To fix this, either:
^

  • Move all stylesheets to the same folder
  • or have one cache per folder