Category Archives: programming

Getting Heroku to run a new app

I’ve been trying to launch a new app. After following the instructions I started running into weird errors. I am also probably not a typical Heroku user.

I had an old Heroku account supposedly using an older RSA public key; I made a new one. Because I have > 2 keys Heroku kept hanging up on me when I tried pushing the master branch. I did an ssh-add -d <KEYNAME> on my main public key, and ssh-add -l confirmed that was gone. Then git push heroku master succeeded. (I had to do an ssh-add later to add back my normal public key.)  Apparently Heroku doesn’t like > 2 keys before disconnecting.

Then there was the issue of me not using Postgres locally. I got the logs via the heroku logs command, and that revealed the message “Please install the postgresql adapter”. I found a StackOverflow post that explained you needed to add the therubyracer-heroku and the pg gems to your :production environment in the Gemfile. The next git push heroku master showed the pg gem being installed.

Still no luck. Another get of the logs revealed “application.css isn’t precompiled”. Oh, right because of the Asset Pipeline stuff. Another post noted the bundle exec rake assets:precompile command.

Next up, the database needed to be set up. (Database migrations were not automatic.) So, I ran: heroku run rake db:migrate, followed by restarting the server: heroku restart.

JavaScript array indexing technique

You’ve probably heard of the Tron in 219 bytes which has the code:

<body id=b onkeyup=e=event onload=
><canvas id=c>

The part of this I really like is:


Because e.which&3 reduces the keystrokes (i, j, k, l) to an array index that is 0-3. That index then selects a value in the moves array: [1, -n, 1, n]. I’m thinking I’ll use this trick to say index into a set of stored numbers or something, even objects:

error_code = {
  "e100": "Error 1",
  "e200": "Error 2",
  "e300": "Some other error"
}['e' + code_number]

(You can’t begin a hash key with a number.)

Configure Rails 3’s I18N load path for subdirectories

If you’re like me you want to use nested directories to organize all of your files, especially when it comes to internationalization (I18N). I just found out about the nifty views trick that uses your current controller and action as the first part of your translation key. For example, let’s say you are looking at a list of all uploads you might be viewing the action:

Inside the template you probably have:

<h1><%= t('.title') %></h1>

Because of the leading dot Rails will be looking for the key defined as (assuming :en locale):

      title: Your title

Since you’re going to have a lot of locale files, you might think of placing the English locale file in:


Which is all well and good until you realize the I18N load path doesn’t include subdirectories. A quick fix to application.rb is all it takes though. Add:

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**/*.{rb,yml}').to_s]

The ** is the magic there.

join() is slower than the

Turns out the Internet was right on this one: if you’re trying to create a big string from little ones it’s faster to << (less-than-less-than operator) on a String than to make an array of Strings and join its elements. Without diving into the Ruby code itself my guess is that strings are linked lists in memory and its end pointer is just moved, whereas making a bunch of array elements means new String objects for each and then having to walk all of the objects to form a new String in the end. (Granted, I’m using Ruby 1.8.7 still!)

Here’s the code:

require 'benchmark' do |x|'join') do
    1_000.times do
      a = []
      1_000.times do
        a << 'This is some string stuff'
  end'<<') do
    1_000.times do
      a = ''
      1_000.times do
        a << 'This is some string stuff'

And the result:

          user     system      total      real
join  1.180000   0.390000   1.570000 (1.571057)
<<    1.090000   0.390000   1.480000 (1.491420)

Double-checking for nil and the Maybe Pattern

While listening to The Ruby Show episode #176 I heard about the ThoughtBot post about the Maybe Pattern as discussed in their “If you gaze into nil, nil gazes also into you” post.

It took me a minute to figure out what was going on. (Maybe I’m just getting slower in my old age.) Plagiarizing from their post, they included the code required to set up the Maybe Pattern and I’ll try to add my own comments in red so I feel like I’m adding something to this conversation:

This is modifying the base Object of which every Ruby object is
a child. Yes, that means even Nil gets an automatic maybe()
method stuck in it.

The idea is that if you think a method *might* return a value
then you ought to return your value with a .maybe() on it.
That accomplishes the "wrapping". You'll see that it takes
itself and returns an instance of Some with itself stuffed
into it. Thus at this point you really get a Some() object
back, not your original return value.
class Object
  def maybe

... Except for Nil. This one definitely is empty/blank/nothing
so we need to create an instance of Some that will throw
exceptions if you try to unwrap it.
class NilClass
  def maybe

And here is the Some object that wraps anything you give
it by storing it in its own @object attribute.
class Some
  def initialize(object)
    @object = object

  This is how you "unwrap" an object. Pay close attention
that the None version of this will throw exceptions.
  def get

  This is one way you can check to see if there might
be values.
  def present?

  And this is the other.
  def blank?

And back to some Magic Sauce. It creates a new error type,
Unwrapped, and will return it when you attempt to call get().
This is because as a consumer of the Some or None values
you ought to have checked present?() or blank?() first. That's 
right, consumers need to be sure that they're not just going
to use a nil value.
class None
  class Unwrapped < StandardError; end

  def get
    raise Unwrapped

  def present?

  def blank?

OK, great. So how do you use this in practice?

When you return a value that is absolutely true or false, then do so. If you think your return value might be null then wrap it by tacking on a .maybe() call.

The consumer of these return values should always check for present?() or blank?(). If something is not present or is blank then you should no longer need to access the return value because, well, you got your answer.

However, if you need to use the return value for something (e.g. it might be a single object, or might be an array, or a Hash, or ...) then you need to check if it's present?() and/or not blank?(). If that's true then you can call the object's .get() method to grab that value and continue with your logic. Like:

accounts = bank(me).accounts
# accounts might be nil ... check present?()
if accounts.present?
  account_list = accounts.get
  # Now account_list definitely has something which isn't nil!

The main thought I had in all of this is that this will create tons of wrapper objects that could just add bloat to your application. Plus there's the extra evaluation involved. In my own code I almost always just use the Rails .blank?() method to check if things are there. That seems to handle nil, empty strings, and empty arrays just fine!

Have your custom Paperclip Processors gone missing?

I’ve been converting a Rails 2.3.8 app into a Rails 3 app and one snafu was figuring out what happened to Paperclip. I use it to actually post-process audio files after upload, in this case slowing them down. I was getting this error:

uninitialized constant Paperclip::SlowerAudioFile:

Which is weird because I checked the readme and it still says to put them in the lib/paperclip_processors. I moved things around, I tried a bunch of little changes to the processor code, but nothing.

It seems the larger problem is just that the lib directory wasn’t being automatically loaded at all. (Turns out someone blogged this.) But by the time I had read that I had already taken the advice of a StackOverflow conversation and had just moved my processor to config/initializers/paperclip/slower_audio_file.rb, the beginning of the code looking like:

module Paperclip
  class SlowerAudioFile < Processor
    def initialize file, options = {}, attachment = nil