I have three XML files that I want to include in a GEM and be able to read information from in the GEM library. Including them in the GEM is not a problem. The problem I am having is accessing them from a method within the GEM library. The XML files are located in the same directory (lib) as the ruby files. How do I need to do within the GEM to load the XML files?
myclass = MyModule::MyClass.new myerrorinfo = myclass.get_error_info(errorcode) puts myerrorinfo[:description]
The get_error_info instance method loads an error.xml file to retrieve additional information for the error code. Everything works fine if I include the code in my apps vendor directory and specify the vendor directory in my load path (./vendor/error.xml). Since this GEM is going to be used for multiple apps, I need to figure out how to load the XML files from the GEM install.
I wont advise to use "require 'mygem'. but add into environment.rb the config.gem clause.
looks like the "not functional"part here is the code of this gem. You need to be more specific ;)
The Ruby load path is where Ruby will look when it needs to load files that define classes, but adding directories to the load path won't help when you want to open a file directly. You didn't include an example of how you're opening the XML files, but I'd guess it looks something like this:
File.open(path_to_xml_file) do |xml_file| ...
Since the code you're using to open the XML file is in the gem your XML file should always be the same location relative to your code file. You can use the
FILE constant to get the absolute location of the current file, and use that to find the absolute location of the XML file. For instance:
xml_directory = File.join(File.dirname(__FILE__), '..', 'xml') ... File.open(File.join(xml_directory, 'foo.xml') do |foo_xml_file| ...
This example assumes you've moved your XML files to their own directory. If you keep your XML files and code file in the same directory you can simply use