Ruby on Rails autoloading causing “uninitialized constant” error

Whilst working on a personal project using the excellent betfair-ng gem that I converted to a ruby on rails project I came across a strange issue Once When running the code I was getting the following error.

1
 uninitialized constant Betfair::Client

It took a while to realise that this was caused by the autoloading feature of rails. However working out what to do to fix it turned out to be a little tricky but actually very simple. All I needed to do was to to move the `require` into the class initializer:

1
2
3
4
5
6
class BetfairCommands
def initialize
require 'betfair'
@client = Betfair::Client('X-Application', app_key)
end
end

I’m still quite new to ruby so don’t really know the full impact of this change, but it seems to work fine so far.

EDIT:

So it turns out that I didn’t need to do that way. I just needed to change the line in the Gemfile from

1
gem 'betfair-ng'

to

1
gem 'betfair-ng', require: 'betfair'

This then meant that I could remove the require from the class completely and rails now hooks it up.