grautur
grautur

Reputation: 30505

Where to put a complex require statement in Rails?

I'm writing some Rails code that I want to be both 1.8.7 and 1.9 compatible. In a couple different files, I do some CSV parsing, so I currently have the following requires line in each file:

if RUBY_VERSION < "1.9"
  require "rubygems"
  require "fastercsv"
  CSV = FCSV
else
  require "csv"
end

To avoid all the duplication, though, this block should probably live in a single place. Where's the best place to put it? Is application.rb the right place?

Upvotes: 1

Views: 69

Answers (1)

rewritten
rewritten

Reputation: 16435

I'd put it in an initializer config/initializers/csv.rb. This is loaded into rails automatically, and does not mix into the load path (so you don't have to bother about the file name).

Just be aware that some loading mechanisms do not do a "require" but just run the file in the loader context, so if you get an exception, you may not deal with it in the usual way.

Upvotes: 2

Related Questions