Bugfix: Rails 2 does not find an association when it is named with a string instead of a symbol

Association named 'variations' was not found; perhaps you misspelled it?

I just was hunting down a strange error with this model:

class Model
  placeholder = 'variations'
  
  has_many placeholder
  
  nested_scope :verbose, :include => :variations
end

Everything, including Model.variations and Model.reflect_on_all_associations.map &:name did work (the latter returned [ :some_association, 'variations' ]).
Eventually, the quotes led me to the solution: I had to write has_many placeholder.to_sym.
...

Fix AssociationTypeMismatch

When you're getting this error, one possibility is that you've created a select field for an association instead of the associated object's id. Example:

form.select :unit, Unit.for_select

will be expected to deliver a real Unit object, whereas

form.select :unit_id, Unit.for_select

will make Rails typecast the String value from the select field to the unit's ID.

Internet Explorer to Start Automatic Upgrades across Windows XP, Windows Vista, and Windows 7

This will hopefully kill IE6 and IE7 for good. The latest available IE for Windows XP is IE8 though.

Writing Ruby Scripts That Respect Pipelines

Guide to writing CLI scripts in Ruby that play nice with pipe chains.

How to deal with MethodNotAllowed errors

One of the most common production errors are ActionController::MethodNotAllowed errors. They usually happen when someone reloads a form by pressing enter/return in the URL field, or by opening JavaScript links incorrectly.

The attached initializer provides a default way to deal with this.

You'll get the following behaviour:

  • if the incorrect request has a HTTP_REFERER coming from the same application, set a flash, and redirect back
  • if the incorrect request has no HTTP_REFERER or one coming from an external source, set a flash...

Make Less interpret the escape codes in a logfile

The unix command line tool less is a good choice for browsing logfiles. In the standard configuration, though, it does not interpret the escape sequences used in the rails logfiles. To enable this type:

less -R my_logfile.log

You can also have an alias to save yourself the typing

alias less='less -R'

Vendor-prefixed CSS Property Overview

A list of CSS vendor-prefixes.

Managing Rails locale files with i18n-tasks

When internationalizing your Rails app, you'll be replacing strings like 'Please enter your name' with t('.name_prompt'). You will be adding keys to your config/locales/*.yml files over and over again. Not to miss any key and place each at the right place is a challenging task.

The gem i18n-tasks has you covered. See its README for a list of things it will do for you.

Note

The i18n-tasks gem does not understand aliases and will duplicate all referenced data when it writes locales. If yo...

Re-enable submit buttons disabled by the :disable_with option

Submit buttons in Rails come with a useful option :disable_with which will disable the button when clicked and change its label to something like "Please wait...".

An annoying side effect of that feature is that when you use the back button to return to the form, the submit button will be greyed out and disabled.

A solution is to re-enable the submit button before leaving the page. This works in Rails 3:

$(window).unload(function() {
  $.rails.enableFormElements($($.rails.formSubmitSelector));
});

Change image scaling algorithms with CSS

List of non-standard CSS attributes that change how the browser resamples scaled images. Only use them if you know 100% which browser the client is going to use. Otherwise just stick with the default.

Useful script to collect downloads from several sites

For university I have to stay up-to-date with lecture documents. Since my university doesn't offer RSS feeds, I wrote a little script that collects files from web pages.

You want this, if you have several web pages that offer downloads that you don't want to check manually. Just register the URL and a CSS snippet to retrieve the files in the attached script and run it – it will fetch all your files. It will store all files in a single place or sort them into respective directories.

Edit the header of the file (providing your data), save it...

How to fix: "500 Internal Server Error" after adding Rack::Bug

When Rack::Bug has been added to your project and your Apache2/Passenger only replies with an Error 500 (Internal Server Error) you won't get any love from both application and Apache logs.

You can start a script/server and try connecting there. It should also fail but you will most likely see this error:

Internal Server Error  
undefined method `new' for "Rack::Bug":String

While the following is (for some reason) working on OSX...

config.middleware.use "Rack::Bug", :secret_key => '...'

...you need to do this so it wor...

Request a gzipped response from a web server using Wget

To reduce download time, application servers usually serve content using gzip compression, if the browser supports it.

When using a tool like Wget to explicitly download an application's response, the server responds with the uncompressed version:

wget http://example.com/

If you are curious about the compressed file's size, pass the corresponding HTTP header:

wget --header="accept-encoding: gzip" http://example.com/

Embed Google Analytics code for some environments only

When you use google analytics to track your visitors interactions, you should ensure that it runs on your production site only. Otherwise it will spoil your statistics. To prevent this, test for the right environment and place the JS-code afterwards:

- if Rails.env.production?
  :javascript
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
    _gaq.push(['_trackPageview']);
    ...

davetron5000/methadone - GitHub

Framework to write command-line apps in Ruby. Comes with a nice way of processing parameter options, some utility classes and Cucumber steps for testing your CLI app.

How to fix "unknown role" errors in Capistrano recipes

When you have a complex recipe setup with multistage deployment you may run into this error:

`role_list_from': unknown role `something' (ArgumentError)

Consider this task definition:

namespace :foo do
  task :bar, :roles => :something do
    # do crazy stuff
  end
end

Whenever we call foo.bar in our recipe, Capistrano will fail if you deploy to a stage where none of the servers has the role the error complains about, "something" in this case.

However, you can [hack around it](http://groups.google.com/group/ca...

Pick a random element from an array in Ruby

[1,2,3,4].sample
# => e.g. 4

If you'd like to cheat and give different weights to each element in the array, you can use the attached initializer to say:

[1,2,3,4].weighted_sample([1,1,1,1000])
# => probably 4

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

Scenario outlines in Cucumber

Scenario outlines allow us to more concisely express repetitive examples through the use of a template with placeholders.

ERB templates and comments

When you use one line Ruby comments in ERB templates you should never do this (notice the whitespace in front of #):

<% # my comment %>

<div>my html</div>

This leads to strange html output. To avoid long debugging sessions, you should never have a whitespace before the # character (but newline is allowed)

<%# this works as expected %>

<%
    # this works, too
    # foo bar baz
%>

Git instaweb

Git has a built-in repository viewer for your web browser. a bit similar (but less awesome) than github.

If you have apache installed, simply go to your repository, and enter
git instaweb --httpd apache2
otherwise, simply install lighttpd and just run
git instaweb

This should open a brower automatically pointing to your repository. If not, try to connect to localhost:1234.

You can stop the server with
git instaweb --stop

Graticule computes NULL distance for some records (and how to fix that)

The SQL code generated by Graticule's spherical distance computation is insufficient and can lead to NULL distances in edge cases.

The reason for this is that MySQL is performing several sine and cosine computations which can result in slight rounding errors -- which is usually okay. Rarely, though, for the exact center of the given circle, it is then asked to compute the arc cosine of a result like 1.0000000001.

Since this i...

Sequel: The Database Toolkit for Ruby

Seems like a useful gem for cases where ActiveRecord is overkill but you don't want to do everything by hand either.

DataMapper Retrospective

I introduced DataMapper on my last two major projects. As those projects matured after I had left, they both migrated to a different ORM. That deserves a retrospective, I think.