Orange
Orange

Reputation: 187

cant load lib directory modules - uninitialized constant - rails 2 to rails 3 upgrade

I'm currently migrating an application in rails v2 to v3

In my lib/ i've some modules in subdirectories, for example, i've the lib/search/host_search.rb

with a

  module HostSearch
    def do_search(args)
       #...
    end
  end

then I need to use it in a controller named Discovery::HostController < ApplicationController :

def search_results
   output = HostSearch.do_search(:search_string => @search_string, 
     :page => params[:page],
     :user => @current_user)
   #...
end

But have I get:

uninitialized constant Discovery::HostController::HostSearch

..I tried to put this lines in application.rb but it doesn't work..

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Upvotes: 6

Views: 5380

Answers (2)

robd
robd

Reputation: 9833

I think if you put the HostSearch module under a search subdir, (ie in lib/search/host_search.rb), then you need to namespace it:

module Search
  module HostSearch
  end
end

If you don't want to namespace it, you can should move the file into the lib root: lib/host_search.rb.

See also: https://stackoverflow.com/a/19650564/514483

Upvotes: 0

rkamun1
rkamun1

Reputation: 338

I found that moving the module to the lib folder or explicitly including the folder to load worked, in your case config.autoload_paths += %W(#{config.root}/lib/search)

I think there's something syntaxical that we are missing. Another thing is that if you don't want to mess with the application.rb file, require the file, which if I remember, takes the file path from the lib folder eg: search/host_search <- check that.

Upvotes: 5

Related Questions