Skip to main content

Benjamin Oakes

Photo of Ben Oakes

Hi, I'm Ben Oakes and this is my geek blog. Currently, I'm a Software Developer at Hedgeye. Previously, I was a Research Assistant in the Early Social Cognition Lab at Yale University and a student at the University of Iowa. I also organize NewHaven.rb. I do development with Ruby, JavaScript, SQL, HTML, and CSS. I have an amazing fiancée named Danielle Smith.

Blog

autoload in Ruby 1.8 and Rails

by Ben

Just a PSA from a recent Ruby discussion:

Ruby’s autoload works fine if you’re using it in a gem that’s loaded once (and need to use it on Ruby 1.8, vs. require_relative in Ruby 1.9+), but if autoload is used in a collection of Ruby classes or modules in a folder that’s in the Rails load path, then it’s probably not a good idea. You’ll get unexpected reloading behavior, at a minimum. That applies to submodules too, of course.

In general, you don’t want to mess with $LOAD_PATH, which was a fairly common practice in 1.8. That’s largely gone away in 1.9 with the advent of require_relative, but many gems need to be backwards compatible. In Ruby 1.8, you can always futz around with __FILE__, but that gets messy as well.

Blocking migration creation in Rails

by Ben

We have a project that accesses a shared database. To prevent problems (and confusion) we wanted to block the creation of migrations in the “secondary” applications so that there was one authoritative place for migrations to live.

It’s easy to accomplish in a simple way.

If you’ve never made any migrations in the secondary application, just do this:

$ echo "NOTE Please do not make migrations in this project.  They should all live in _primary app_." > db/migrate

That way, when you run rails g migration foo, you’ll get this:

$ rails g migration foo
      invoke  active_record
      create    db/migrate/20111129162804_foo.rb
[...]/ruby-1.9.2-p180/lib/ruby/1.9.1/fileutils.rb:243:in `mkdir': File exists - [...]/db/migrate (Errno::EEXIST)

When you try to cd into that directory, you’ll get this:

$ cd db/migrate
bash: cd: db/migrate: Not a directory

After you get over the initial “wha?” reaction, you’ll look at db/migrate and see the message:

$ cat db/migrate
NOTE Please do not make migrations in this project.  They should all live in _primary app_.

Pretty nice, right?

Using Heroku with an external MySQL database

by Ben

We recently had a need to use Heroku with an external MySQL database. Thankfully, there was already a gem that solved the problem. However, it didn’t have that much by the way of documentation, so I wrote this up and contributed it to the author. Also, I added X.509 support, which we required.


NOTE: After my pull requests are merged, you should look to the main repository’s README which has a copy of the below.


Example: MySQL with a CA Certificate

In this example, we are setting up a connection to an external MySQL server using the default initializer.

What we have:

First, we configure Heroku with the appropriate environment variables:

# You may have to specify the app name or remote name here via --app or --remote, respectively
heroku config:add EXTERNAL_DATABASE_CA='ca-cert.pem'
heroku config:add EXTERNAL_DATABASE_URL='mysql://username:password@server/dbname'

By default, heroku_external_db looks for the CA cert in
config/ca, so we need to commit it:

mkdir -p config/ca
cp path/to/ca-cert.pem config/ca
git add config/ca
git commit -v # Using -v since we want to make sure the contents are what we expect (e.g. not a private key)

Additionally, we need the mysql gem in our Gemfile since we are setting up a MySQL server:

echo "gem 'mysql', '~> 2.8.1'" >> Gemfile
bundle install # Need Gemfile.lock too

Keep in mind that Heroku installs its own database.yml for Rails apps and we have to install pg as well. Unfortunately, shared databases are mandatory (but are free).

$ heroku addons:remove shared-database:5mb
-----> Removing shared-database:5mb from our-app... failed
 !     Shared databases cannot be removed

PostgreSQL may still be useful to you if, for example, you want to have feature toggles in a local database, but the main data kept externally. However in our case, it also means all developers will need MySQL and PostgreSQL running locally, which is unfortunate.

One workaround is only installing pg in production:

# File: Gemfile

# *Only* needed on production.
group :production do
  gem 'pg', '~> 0.11.0' # Regardless of whether you plan to use the database or not, Heroku requires you have 'pg' installed.
end

Then bundle like so:

$ bundle install --without production

With our gems updated, commit:

git commit -av # Commit Gemfile and Gemfile.lock

Another option may be overriding database.yml somehow, although it would add complexity. For more info, please see stackoverflow.com/questions/4204724/strategies-for-overriding-database-yml.

With our dependencies out of the way, we can move on to testing the connection.

If you are making a new application, you may wish to have a simple MVC for testing that the connection works. E.g., for a blog style application with posts do:

rails generate scaffold post
# NOTE you probably want to change the default "Post.all" to "Post.limit(5)" or something similar
git add .
git commit # ...
# Don't forget to set a default route, etc.

With all these changes committed, we can deploy to our Heroku app:

git push heroku master # Your remote may be different

Now, since we are connecting to an existing database, we don’t need to run any migrations. (Keep in mind that when sharing a database, it is best to have one authoritative source for migrations to live.) If in your situation you’re creating a new database, you may need to do that, run migrations, seed the database, etc at this point.

Open our-app.heroku.com and we should see our data. If you happen to run into a problem, please check the logs first:

heroku logs --tail # Again, you may need to specify an app

If you are having a problem, a good starting point is double checking your passwords, usernames, security settings, etc.

Example: MySQL with X.509

The process is very much the same as the above example, except two extra environment variables and files are required. Below are the extra steps.

What we have:

First, we configure Heroku with the appropriate environment variables:

heroku config:add EXTERNAL_DATABASE_CA='ca-cert.pem'
heroku config:add EXTERNAL_DATABASE_CERT='client-cert.pem'
heroku config:add EXTERNAL_DATABASE_KEY='client-key.pem'

By default, heroku_external_db looks for the files in config/ca, so we need to commit them:

mkdir -p config/ca
cp path/to/ca-cert.pem path/to/client-cert.pem path/to/client-key.pem config/ca
git add config/ca
git commit

The rest of the process is the same as in “MySQL with a CA Certificate”.

RubyConf 2011

by Ben

RubyConf 2011 logo

RubyConf 2011 was a blast. It was great to meet other Rubyists, get a ton of T-shirts (no really, I got 8 or so), and talk Aaron Patterson into giving Jonathan Magen a special message.

If you weren’t able to go, I pushed my notes up to a public GitHub wiki. A couple others from Hedgeye are adding their notes as well, so with those (plus the Confreaks videos when those guys finally have access to a reliable Internet connection), it’s almost like you were there.

ActiveRecord::ConnectionNotEstablished in Rails 3.1 on Heroku

by Ben

We have a simple application that doesn’t have an ActiveRecord dependency. It’s deployed to Heroku, and it’s been working fine on Rails 3.0.x since April 2011. We knew we weren’t using ActiveRecord for database connectivity, but we let it be, since it wasn’t causing any issues.

When upgrading to Rails 3.1, we found that every single page would give ActiveRecord::ConnectionNotEstablished on our staging environment on Heroku. The same error didn’t happen in development. Although we might have been able to get gem 'pg' set up and working, we really didn’t need an ActiveRecord dependency at all.

I found part of a solution on StackOverflow, but it needed a little tweaking for Rails 3.1.0.

# File: config/application.rb

# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"

That’s what Rails 3.1.0 generates when running rails new myproject --skip-active-record. (Note that require "active_record/railtie" is commented out.) This solved our ActiveRecord::ConnectionNotEstablished problem, but gave us a few others, namely:

Fixtures

There’s some normal stuff to get rid of in terms of spec_helper.rb and/or test_helper.rb. Here’s an example:

# File spec/spec_helper.rb

# # If you're not using ActiveRecord, or you'd prefer not to run each of your
# # examples within a transaction, remove the following line or assign false
# # instead of true.
# config.use_transactional_fixtures = true

You may have others. Tarantula had to be adjusted for us, for example.

ActiveRecord::RecordNotFound

ActiveRecord::RecordNotFound, however, was an interesting problem. Everything worked fine without ActiveRecord except the places where we were using ActiveRecord::RecordNotFound to give a HTTP 404 to the user agent. That seems strange in a lot of ways, because a 404 shouldn’t have anything to do with your chosen ORM. My first intuition was to do require 'active_record/errors' (see also the Rails docs), but that caused problems with assumptions in 'rspec/rails'.

Right now, the below is what we ended up with:

# File: config/application.rb

# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"

# For errors like ActiveRecord::RecordNotFound
require "active_record"

Our automated tests (Rspec, integration tests, Tarantula, Selenium, etc) all pass with it and we no longer get ActiveRecord::ConnectionNotEstablished, but we still have an ActiveRecord dependency I don’t like. (There must be another error we can raise — I don’t entirely like the render '/404.html', status: 404 solution for several reasons.)

relative_time_ago in Padrino should be time_ago_in_words

by Ben

You might find relative_time_ago referenced in the Padrino Guides or Padrino Helpers RDocs, but that doesn’t exist.

According to the Application Helpers guides, you probably want distance_of_time_in_words or time_ago_in_words.

Example:

%p
  = time_ago_in_words(my_date)
  ago

For reasons I don’t quite understand, this documentation is also incorrect:

time_ago_in_words(2.days.ago) => "2 days ago"

The actual behavior is:

time_ago_in_words(2.days.ago) => "2 days"

I’m planning to move some of this into the padrino-framework project directly. Incorrect documentation is worse than no documentation; maybe it will be more accurate if kept in the code. :)

Accessing Cookies in Padrino/Sinatra

by Ben

Unlike in Rails, there is no global cookies object in Padrino or Sinatra. Instead, you need to use request.cookies within your request handler:

get :index do
  my_value = request.cookies['my_value']
end

Enforcing SSL in Padrino

by Ben

We’re trying rack-ssl-enforcer out on our Padrino-based project. It seems to work when configuring like so:


# File: app/app.rb
class MyApp < Padrino::Application
  # [...]
  configure :production do
    require 'rack-ssl-enforcer'
    use Rack::SslEnforcer
  end
end

We're using it with Padrino with some success. It's great that such a common need is really simple to set up. However, even after looking through the docs further, I'm surprised that I can request over HTTP and I don't get redirected to HTTPS. I've yet to figure out the issue, but it seems to meet our needs just fine otherwise.

This is in response to Dan Mayer's article Force all Sinatra traffic to https. I had started to comment, but his blog errored-out when submitting. Thanks for posting it, Dan!

New open source projects: Maid and TabCarousel

by Ben

I’ve been hard at work taking some code I had originally written for myself and packaging it up as two open source projects. I’ve been very happy about the amount of interest I’ve received in both. I encourage you to take a look and see if what I’ve released would be useful to you. Feedback (and contributions) are welcome!

Maid

(Install, Source Code)

Be lazy! Let Maid clean up after you, based on rules you define.

Maid keeps files from sitting around too long, untouched. Many of the downloads and other files you collect can easily be categorized and handled appropriately by rules you define. Let the maid in your computer take care of the easy stuff, so you can spend more of your time on what matters.

Think of it like the email filters you might already have, but for files. Worried about things happening that you don’t expect? Maid doesn’t overwrite files and actions are logged so you can tell what happened.

Maid is inspired by the Mac OS X shareware program Hazel. This tool was created on Mac OS X 10.6, but should be generally portable to other systems. (Some of the more advanced features such as downloaded_from require OS X, however.)

Your rules are defined in Ruby, so easy rules are easy and difficult rules are possible.

TabCarousel

(Install, Source Code)

A Chrome extension to help you keep tabs on info you want to monitor. It’s great for cycling through tabs on an external display, like a TV.

TabCarousel is simple: open tabs you want to monitor throughout the day, then click the toolbar icon. To stop, click the icon again.

By default, TabCarousel will flip through your tabs every 15 s, reloading them every 5 min. It’s great on a unused display or TV. Put Chrome in full-screen mode (F11, or cmd-shift-f on the Mac) and let it go.

If you want to change how often TabCarousel flips through your tabs, right click on the toolbar icon and choose “Options”.

Example Uses

On a HDTV that has a computer attached, open the NewRelic overview (and Background Tasks, etc.) for each app you’d like to monitor. Set NewRelic to kiosk mode for each page, then hit the “Tab Carousel” toolbar button.

The TabCarousel wiki has more.

throw/catch vs. raise/rescue

by Ben

Just a piece of Ruby trivia: Ruby has both throw/catch as well as raise/rescue. Most newbie Rubyists don’t know this. There’s a section of the Pickaxe book that discusses them both.

Essentially, rescue is used for exceptions and error control while catch is used for symbols and flow control. The idea is that you shouldn’t use exceptions to change the flow of your program, but rather to handle errors.