$" surviving between calls
I have an odd situation where $" seems to 开发者_如何学编程be surviving between calls, but nothing else does. It's returning properly the first call, and fail each additional request. This should be global information, so It won't work just to put it in a session.
The comments show what logging returns, but my experience with "FileImport.installed_formats()" is that the first time I load a page populated by it, it properly returns ["CSV","FixedText"]. I call FileImport.installed_formats() multiple times in the same call, for test purposes, and it works fine. However, when I refresh the page, the method is returning an empty array.
What's the "best" fix? I don't really want to destructively remove $" each time, since I know the server is trying to cache the classes. Is there a cleaner way to view the installed classes without the Class.constants method?
def FileImport.installed_formats()
FileImport.require_import_folder()
return FileImport.constants
end
def FileImport.require_import_folder()
logger = RAILS_DEFAULT_LOGGER
#this is giving me what I expect... ["lib/file_import/fixed_text.rb", "lib/file_import/csv.rb"]
logger.debug("WHY? " + Dir["lib/file_import/*.rb"].inspect)
#This is giving me two different things:
#First run: []
#Second run: ["lib/file_import/fixed_text.rb", "lib/file_import/csv.rb"]
logger.debug(($".select {|v| v =~ /file_import/}).inspect)
Dir["lib/file_import/*.rb"].each do |i|
i.sub(/lib\//,"")
# $".delete(i) #I'd rather not do this, if there's a cleaner way...
require i
end
#first time, this gives what i want: ["CSV", "FixedText"]
#When I refresh, I get [] instead...
logger.debug("SHOULDINSTALL: " + FileImport.constants.inspect)
#Both times this gives the expected: ["lib/file_import/fixed_text.rb", "lib/file_import/csv.rb"]
logger.debug(($".select {|v| v =~ /file_import/}).inspect)
end
I'm not happy with the behavior of rails here, but it seems buggy (that it both assumes a module is explicitly available, but doesn't list it as such).
I resolved this by caching the names of installed modules.
def FileImport.installed_formats()
FileImport.require_import_folder()
installed_formats = Rails.cache.read("installed_upload_formats") || []
installed_formats = (installed_formats + FileImport.constants).uniq
Rails.cache.write("installed_upload_formats",installed_formats)
return installed_formats
end
精彩评论