gammons/fake_arel - GitHub

Gem to get Rails 3's new ActiveRecord query interface (where, order) and the new scope syntax (chaining scope definitions) in Rails 2.

You also get #to_sql for scopes.

marcandre/backports - GitHub

Gem to get Ruby 1.9 features in Ruby 1.8.

How to install a specific version of RubyGems (and how to downgrade)

Sometimes you want one distinct version of RubyGems to be installed to replicate the same behavior across multiple servers.

Usually would do this to update your RubyGems, but this always takes you to the latest version:

gem update --system

While there are ways around the interwebs that use the rubygems-update package and call its setup.rb, there is an undocumented switch you can use:

gem update --system 1.3.7

This updates to the given version, 1.3.7 in the above case, by walking the rubygems-update package way itself.

---...

Improved gitpt now part of geordi

Our gitpt script to generate git commits from Pivotal Tracker stories has been tweaked and polished and is now part of the geordi gem.

Install the freshly released version 0.7 now:

gem install geordi

This update will bring you commit with an initial "setup wizard" (that asks for your PT API key and initials) and prettier output: stories are colored by their state and thos...

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

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

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.

Rails ERD – Entity-Relationship Diagrams for Rails

Gem to generate entity relationship diagrams from your Rails 3 ActiveRecord models. The diagram style is pretty and configurable.

ActsAsTaggableOn: Cache tag lists

For performance improvements (and to remove the need for eager loading), the ActsAsTaggableOn gem supports caching your tag lists directly in your model. To enable this, simply add a cached_tag_list column to your table.

Example:

class Company < ActiveRecord::Base
  acts_as_taggable_on :categories
end

The cache column has to be named cached_category_list.

Existing data

If you already have existing data, you have to save all records with tags once, after you've added the ...

Configuration for Rails, the Right Way

I still see people promoting various gems and plugins to handle miscellaneous configuration elements for your application. One little known secret is that Rails 3 allows you to define your own configuration elements trivially.

Excel files can't hold more than 65535 rows per worksheet

"Classic" Excel (XLS) has a magic limit of 65535 rows per worksheet. This was fixed in XLSX but the version used by the Spreadsheet gem can only write XLS files.

If you want to write more data, consider hacking around it using in_groups_of and writing multiple column sets of your data (i.e. split 1 block of 3 columns and 100000 rows into 4 blocks of 3 (12 in total) columns and 25000 rows).

You can do this until you reach the other limit of 256 columns. After that, open up a new workbook or consider a ...

Find geocoded records that are close to a location (radius search)

When you have objects in your database that hold latitude and longitude and you want to find others that are close to given coordinates you can use the Graticule gem.

Graticule

Graticule offers several methods to compute the distance between two geo-dated objects but fetching records from the database that are within a given radius of a location is a bit trickier:

def close_destinations(latitude, longitude)
  distance_sql = Graticule::Distance::Spherical.to_sql(:latitude => l...

Run a script on the server

You have to specify the environment with -e env_name or RAILS_ENV=env_name if you want to run a script on the server.

at Rails 2 it's script/runner

bundle exec script/runner -e env_name path/to/script.rb argument1 argument2 ...

at Rails 3 it's rails runner

RAILS_ENV=env_name bundle exec rails runner path/to/script.rb argument1 argument2 ...

Be careful with "memoize"

ActiveSupport's memoize has a dangerous feature you might not know about.

Assume you have

class DeepThought
  extend ActiveSupport::Memoizable

  def life_universe_and_everything
     # some lengthy calculation returning 42
  end
  memoize :life_universe_and_everything
end

Then #life_universe_and_everything will of course cache the result after calculating it once. However, you can trigger a recalculation by calling #life_universe_and_everything(true).

If, however, your method looks like

de...

"Show me the page" fails to open a browser window

If you get an error like this:

Unable to launch /home/bruce/Projects/myproject/tmp/capybara/capybara-201110311210111407691101.html 

... update your launchy gem. It failed for us in version 0.4.x. We could fix the issue by upgrading to 2.0.5.

Rails 3.1 error message: Could not find a JavaScript runtime

After starting the Rails server in a freshly generated Rails 3.1 project you could see an error message such as

/usr/lib/ruby/gems/1.8/gems/execjs-1.3.0/lib/execjs/runtimes.rb:50:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

Just add a JavaScript runtime to your Gemfile and the error vanishes.

Examples:

gem 'therubyracer'
gem 'extjs'

How the Clearance gem remembers and clears sessions

Clearance is a gem that provides authentication functionality (e.g. login, logout). This note explains, how the clearance login, logout and (in old Clearances) remember me functionality works.

Login

Clearance defines a database column called "remember_token". When you login in, that token will be saved in a cookie. For that reason you don't have to re-sign-in when you close and open the browser again.
This also means that you can be logged in in more than a single browser. Also see [When ses...

Cucumber.yml was found, but could not be parsed.

If you encounter the error message above when running cucumber, just execute...
rm rerun.txt
...in the Rails directory.

Or run...
tests
...from the geordi gem. This will do the work for you automatically.

Monitor a Rake task with God

In order to monitor a Rake task using God your Rake file must write a file with its process ID (PID) to a path determined by God. This way God can check whether the Rake process is still alive.

Here is how to do this: In your God config, call the Rake task with an environment variable PIDFILE. This variable should equal the PID file path desired by God:

God.watch do |w|
  w.dir = "#{rails_root}"
  w.name = "my_task"
  w.interval = 10.seconds
  w.pid_file = "#{rails_root}/tmp/pids/#{w.name}...

Mailcatcher: An alternative to inaction_mailer

Looks simpler than inaction_mailer:

gem install mailcatcher
mailcatcher

Setup Rails to send mails to 127.0.0.1:1025. Usually you want the following config in config/environments/development.rb and maybe in test.rb or cucumber.rb.

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address => 'localhost',
  :port => 1025
}

Now you can see sent mails in your browser when opening http://127.0.0.1:1080

Note: In order to s...

Properly adding fields with default values to a model

When adding a new field to your model's database table, don't set any defaults in the database.

It makes people wonder why they get such values when reading attributes.\
Why? Because nobody looks at the database layout since such things are part of your application's logic -- and thus they belong into the corresponding model.

How to

Do it like this:

  • In your migration, after adding the field, update all fields to your desired default:

    update "UPDATE users SET locked = #{quoted_false};"
    
  • In your model, set a defau...

Install the Oniguruma gem

Oniguruma is an advanced regular expression engine for Ruby.

Install Oniguruma with binary dependencies like this:

sudo apt-get install libonig2 libonig-dev
sudo gem install oniguruma

On the Mac do:

brew install oniguruma
sudo gem install oniguruma

Change / Update SSL certificate for Amazon Elastic Load Balancer

There is a new card about how to do this with the new AWS Command Line Interface


At first you need the IAM Cli Tools.
-------------------------------------------------------------------------------------------------------------...

How to fix: Gems are unavailable although they are installed

  • If Rails or Rake are complaining about a missing gem that is listed in your Gemfile.lock and the listed version is properly installed, something is seriously wrong and needs to be fixed.
  • If you accidently executed bundle install some_gem although you wanted bundle update some_gem

What is wrong

Let's say your Gemfile asks for some-gem which you can see when running gem list but bundle show some-gem just gives you an error:

Could not find gem 'some-gem', in any of the sources

Another indicator: Doing a `...