Pregunta

One of my ruby classes draws data from a rather large, local, XML file that will only change with a new deploy.

Is the best practice in this case to keep the document as a constant, like:

class Product 
  XML_DOC = Nokogiri::XML(open("#{Rails.root}/myxmlfile.xml"))
end

or to access the document through a class method, like:

class Product 
 self.xml_doc
    Nokogiri::XML(open("#{Rails.root}/myxmlfile.xml"))
  end
end

I think that the class method may be the way to go, since it will be easier to mock in tests, but what's considered the best-practice for keeping an in-memory file like this?

¿Fue útil?

Solución

This is the most common idiom:

class Product 
    def xml_doc
       @@xml_doc ||= Nokogiri::XML(open("#{Rails.root}/myxmlfile.xml"))
       return @@xml_doc
    end
end

The ||= operator says "if the variable is nil, calculate the result of the expresion and store it, otherwise do nothing". This idiom is called "memoization".

Do no think of constants as a way to optimize your code, in Ruby they are not really constant anyway.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top