Anar Anar - 2 years ago 85
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"))

Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download