Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, app/data/myxml.xml.

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"))
like image 389
Anar Avatar asked Jan 28 '26 01:01

Anar


1 Answers

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"))
like image 177
Scott S Avatar answered Jan 30 '26 14:01

Scott S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!