BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11663

Models have access to text files in Rails?

As a learning exercise, I'm trying to convert an existing Sinatra app to a Rails app. The information in countries.txt will eventually be moved into a database, but in order to keep things simple for me, I'd like to first read data in from the text file, in the same way the source app did. Problem is I can't figure out where File will read from in a Rails app. Where in the Rails directory do I put the countries.txt document for a method in a model to have access?

def get_random
  content = File.read("countries.txt")
  words = content.split("\n")
  words[rand(words.size)].upcase
end

Upvotes: 2

Views: 357

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

I don't have a good suggestion on where to put countries.txt, but let's say you put it in the 'config' directory. You could then use the following to read it, regardless of what file is doing the reading.

content = File.read(File.join(RAILS_ROOT, 'config', 'countries.txt'))

However, if you don't want them in the database, there aren't that many countries... I would consider creating a file in say config/initializers/countries.rb that had something like this:

COUNTRIES = ['Country 1', 'Country2', etc...]

Or a hash mapping the name to the iso code. The advantage to this is you're only reading the file once, not every time you need to get a random country.

But with all that said.. you could also use one of the country gems that are out there to deal with it for you.

Upvotes: 4

Related Questions