Anar Anar - 10 months ago 50
Ruby Question

How to read file in Rails style

I have some data stored as an XML file. I put it into a directory I've created,


Now I want to parse it using Nokogiri. To locate the file I am referencing an absolute path:

@doc = Nokogiri::XML(open("/home/me/webA/myrailsproject/app/data/myxml.xml"))

The absolute path definitely make the code ugly. Is there a shorter, cleaner way to reference the file? Such as:

@doc = Nokogiri::XML(open("myxml"))


The current directory in a Rails is the application root, so you could just do

@doc = Nokogiri::XML(open("data/myxml.xml"))

Or if you want to be sure, you can use the RAILS_ROOT constant -

@doc = Nokogiri::XML(open("#{RAILS_ROOT}/data/myxml.xml"))