6

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/**/"]
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
Orange
  • 187
  • 1
  • 5
  • 11

2 Answers2

5

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.

rkamun1
  • 338
  • 1
  • 2
  • 15
0

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

Community
  • 1
  • 1
robd
  • 9,646
  • 5
  • 40
  • 59