Open a MySQL shell using credentials from database.yml

In order to open a MySQL shell without the need to enter user and password, you can say the following in any Rails 2 project:

script/dbconsole -p

In Rails 3 you can say:

rails dbconsole -p

If you'd like to enter a database for an environment other than development you can say:

script/dbconsole -p staging

MySQL: For each group, retrieve a comma-separated list of values in a given column

The technique described in this card has an important caveat: The result of GROUP_CONCAT is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. This will cause horrible, data-destroying bugs in production. For this reason you should probably not use GROUP_CONCAT ever. At least you must set the value of group_concat_max_len to an insanely high value on every database server your application runs on.


Lik...

Using heredoc for prettier Ruby code

You can use heredoc to avoid endlessly long lines of code that nobody can read. Heredoc strings preserve linebreaks and can be used like this:

def long_message
  puts(<<-EOT)
    Here goes a very long message...
    Sincerely,
    foobear
  EOT
end

<<-EOT will be somewhat of a placeholder: anything you write in the line after you used it will be its value until you write EOT in a single line.

You can use any string to flag your heredocs. To be more verbose you...

Couldn't create database for ...

When you run rake db:create and get this error message

Couldn't create database for {"encoding"=>"utf8", "username"=>"root", "adapter"=>"mysql", "database"=>"project_development", "password"=>"topsecret"}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation)

make sure the user you have specified (root/topsecret) in your database.yml has access to MySQL. You can check this by running mysql -uroot -p.

Solving "cannot remove Object::ClassMethods"

Most likely you run rake and your code is causing an exception which is not the one shown in your terminal.

Rails tries to catch this exception and clean up constants but -- while it's still booting up -- fails on this which causes another exception:

rake aborted!
cannot remove Object::ClassMethods

Running rake with the --trace parameter will give you no love; the backtrace is useless in most cases.

Try these approaches:

First: Check if there is a helpful error message

  • Ha...

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;
    

...

Machinist's #make breaks on has_many associations when defining method `empty?`

Observed on Rails 2.3 and machinist 1.0.6

Like the title says, when you define the method empty? like in the following example, you may not longer use collection.make.

class Book

  has_many :pages

  def empty?
    pages.empty?
  end

end

Assuming

b1 = Book.find(1)
b2 = Book.find(2)

instead of expected

b1.pages.make #=> #<Page id: 1, book_id: 1>
b2.pages.make #=> #<Page id: 2, book_id: 2>

you'll get

b1.pages.make #=> #<Page id: 1, book_id: 3>
b2.pages.make #=> #<Page id: 2,...

dbconsole in Rails 3 requires the environment as the first argument

There is a bug in Rails 3's dbconsole script, which makes the following command open a database console for the development environment:

rails dbconsole -p test

You need to write this instead:

rails dbconsole test -p

Rendering a custom 404 page in Rails 2

Simple: Tell the application controller how to handle exceptions, here a RecordNotFound error.
Do this with the following line:

# application_controller.rb

  rescue_from ActiveRecord::RecordNotFound, :with => :render_404

This will call the method render_404 whenever a RecordNotFound error occurs (you could pass a lambda instead of a symbol, too).
Now write this method:

def render_404
  render 'errors/404', :status => '404'
end

Finally create a 404 document views/errors/errors.html.haml.

%h1 Record...

Rails 3.1.0 has been released!

jQuery as new default Javascript library, streaming response support, attr_accessible with roles, prepared statements, easier migrations.

Invoices: How to properly round and calculate totals

While it might seem trivial to implement an invoice that sums up items and shows net, gross and vat totals, it actually involves a lot of rules and caveats. It is very easy to create invoices where numbers don't add up and a few cents are missing. A missing cent is a big deal for an accountant, so it is important for your invoices to list correct numbers.

Note that this is not legal advice. Also note that while this note has a number of code examples in Ruby and MySQL, the concepts apply to all programming languages and data stores.

When ...

Always show all form errors during development

You've been there: A form cannot be submitted, but you don't see a validation error because the field at fault has no corresponding input field on the form. Because this is usually a bug, you insert debug information listing all errors into the form view. And once the bug is fixed, you forget to take out that debug information.

There is a better way. By copying one of the attached initializers into config/initializers, your forms will always render a small box listing all form errors in the bottom right corner of the screen. This box is n...

Timecop creates records in the past after calling Timecop.freeze

This is a bug in Timecop 0.3.4 or lower. You should upgrade to 0.3.5.

An ActiveRecord is invalid, but has no errors

Did you return false in a before_validation callback?

Random list of ActiveSupport goodies

I recently browsed through the ActiveSupport code and found some nice stuff I did not know about:

ActiveSupport::Callbacks

ActiveRecord-like callbacks, if you need callbacks in non ActiveRecord objects

ActiveSupport::MessageEncryptor

encrypt and decrypt ruby objects

[ActiveSupport::MessageVerifier](https://github.com/rails/rails/blob/mast...

Ruby GetText will eval scripts containing ActiveRecord classes

When the Ruby parser module of Ruby-GetText comes across a file in one of its search directories (e.g. lib/scripts/) and finds out that you are defining ActiveRecord classes inside it, it evaluates the whole file. Here is how to avoid that.

What's happening?

Let's say you have the following script which is only run once, manually, via script/runner:

# lib/scripts/doomsday.rb
class User < ActiveRecord::Base; end
User.destroy_all

In that case we ...

List sizes of MySQL databases

Do you wonder which databases are actually taking up how much space but only have one huge ibdata1 in your /var/lib/mysql and the directories inside your mysql data directory don't represent the actual database sizes? This is for you!

Run from a mysql root console:

SELECT table_schema AS "Database name", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema;

This will get you a result like the following:

+----------------------+--------------+
| Database name    ...

How to change the font in Sublime Text 2

Open up your "Base File.sublime-settings" (Preferences Menu → File Settings – User) in Sublime Text 2. Add entries for font_face, and optionally font_size, so it looks similar to this:

{
  "font_face": "Envy Code R",
  "font_size": 11.5
}

Cool: when you save the configuration file, changes will be applied instantly.

Solve issues with Samsung TV as computer screen

We have a big flat screen TV (Samsung LE46c650l1kxxu) in our conference room. Configuring it properly, we were encountering some issues.
This is a list of issues, providing a solution to each.

No sound with DVI/HDMI and separate audio

There are some inputs on the side of the TV. These will not work for split video and audio.
On the back are more inputs you might not have seen. Choose HDMI/DVI as video in and Audio in for HDMI/DVI as audio in. Do not use RCA audio input but the [...

Create RAID on Amazon EC2 EBS volumes

If you use Amazon AWS cloud services you definitively want to utilize software raid for IO intensive stuff such as database data directories and the like.

Here's how you create it:

  • Create some EBS volumes within management console or
  • sudo mdadm --create -f /dev/md0 --chunk=256 --level 10 --raid-devices 4 /dev/sdf /dev/sdg /dev/sdh /dev/sdi
  • Create a fs on /dev/md0 using mkfs*-tools
  • As soon as this is running, you should do that:
    sudo mdadm --detail --scan >> /etc/mdadm/mdadm.conf

Make sure the last line in `/etc/mdadm/md...

Marry Date::Performance and Spreadsheet gems

Date::Performance is a gem that replaces various method in Ruby's Date class with fast C implementations. Unfortunately it doesn't fully implement an internal method (Date.ajd_to_jd) which makes your code blow up when you use it together with the Spreadsheet gem.

A solution is to restore the Ruby implementation of this particular method. To do this, copy the attached file to lib/fix_date_performance.rb to config/initializers.

How to: Store multiple Vim commands in macros and recall them

Vim allows recording a batch of commands as a macro. This is handy if you need to do the same things over and over.

Here is how:

  1. Press q to enter macro mode.
  2. Press a letter (not a number!) key to assign a slot to your macro.
  3. You are now recording. Do whatever you want with usual commands.
  4. Once you are done, press q again to stop recording.
  5. You can now run your recorded macro by pressing @ and its assigned letter key.

Cheats:

  • If you want to run a macro repeatedly, type a number before pressing the @ key. Example: ...

Always store your Paperclip attachments in a separate folder per environment

tl;dr: Always have your attachment path start with :rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/.


The directory where you save your Paperclip attachments should not look like this:

storage/photos/1/...
storage/photos/2/...
storage/photos/3/...
storage/attachments/1/...
storage/attachments/2/...

The problem with this is that multiple environments (at least development and test) will share the same directory structure. This will cause you pain eventually. Files will get overwritten and...

How to grep through the DOM using the Capybara API

When your Cucumber feature needs to browse the page HTML, and you are not sure how to express your query as a clever CSS or XPath expression, there is another way: You can use all and find to grep through the DOM and then perform your search in plain Ruby.

Here is an example for this technique:

Then /^I should see an image with the file...