I want to extend core Array class with simple method:
class Array
def to_hash
result = Hash.new
self.each { |a| result[a] = '' }
result
end
end
I put array.rb into lib/core_ext and tried to require it in application.rb by
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
But still get undefined method 'to_hash' for ["var1", "var2", "var3"]:Array if tried to use it in model method. Of course I rebooted the server after code changes.
Once way you can do this is by adding the following to one of the files in
config/initializersAll your
autoload_pathsconfig value does is make the paths available for when the classes/files are requested. In my app I might have some file structure as followsIn my
deefour.rbI haveand inside
config/initializersI have adeefour.rbfile containing simplyThe only way the autoload config value you set will cause Rails to look auto load
lib/deefour/core_ext.rbis if you had some call to a classDeefour::CoreExtthat existed in that file. This is why myrequire 'deefour'line in the initializer knows to autoload thelib/deefour.rbfile.The explicit
require 'deefour/core_ext'inlib/deefour.rbserves the same purpose, since it too does not follow the standard class-name-to-directory mapping Ruby/Rails will expect.