11

I am attempting to access a function in a module that is located in the lib directory of my app. (lib/search.rb)

I am actually trying to get zip code searching working from: http://joshhuckabee.com/simple-zip-code-perimeter-search-rails

lib/search.rb

module Search
  def zip_code_perimeter_search(zip, radius)
   #code
  end
end

I am trying to call the zip_code_perimeter_search function from the rails console or from my controller, both times I get undefined method. Any ideas?

Chris Muench
  • 17,444
  • 70
  • 209
  • 362

2 Answers2

16

In your console/controller:

include Search
zip_code_perimeter_search(zip, radius)

In case it doesn't auto-load in Rails 3, in your config/application.rb file, you can do this:

# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/lib/**/"]
Shreyas
  • 8,737
  • 7
  • 44
  • 56
  • 1
    Thanks, I also had to do a require for lib/search. I guess rails 3 doesn't autoload lib. – Chris Muench Mar 07 '11 at 15:43
  • I've edited the answer. If you configure the load directories setting in your application.rb file, you won't need to 'require' the file. – Shreyas Mar 07 '11 at 15:59
  • I'm attempting the same thing, but I keep getting this error when I try to access my module even after modifying the config as you've outlined above. Its crashing on this line: `include Scrape` and throwing this error `uninitialized constant Admin::AdoptionsController::Scrape` – Paul Pettengill Sep 05 '12 at 04:47
2

For calling a module method directly include it in a class and then call it on class instance.

Class call_module_method
    include Search
end

Now

call_module_method.new.zip_code_perimeter_search(zip, radius)

will evaluate the code inside method zip_code_perimeter_search(zip, radius)

Santosh Sindham
  • 879
  • 8
  • 18