kamilk
kamilk

Reputation: 4049

How can I omit the module name when using autoloaded classes in Ruby on Rails?

Let's say I've got the following files:

|- app
|  |- helpers
|  |  |- application_helper.rb
|- config
|- |- application.rb
|- lib
|  |- my_module
|  |  |- my_class.rb

I'm trying to make Rails autoload my_module. In application.rb I set

config.autoload_paths += %W(#{config.root}/lib)

I've also managed to obtain the secret knowledge that in order for autoloading to work, the names of modules and classes must match the names of directories and files, so my_class.rb looks like this:

module MyModule
  class MyClass
    # ...
  end
end

Now I want to use MyClass in my application_helper.rb:

module ApplicationHelper

  include MyModule

  def some_method(active_entry = nil)
    someobject = MyClass.new
    #...
  end

end

But I'm getting an error

uninitialized constant ApplicationHelper::MyClass

In order to make this code work I must replace

someobject = MyClass.new

with

someobject = MyModule::MyClass.new

which is ugly. I thought that the include would work like a C++ using namespace, C# using or Java import but apparently it doesn't. So is there any equivalent to the above statements in Ruby?

Upvotes: 0

Views: 656

Answers (2)

Tom Harrison
Tom Harrison

Reputation: 14078

@ChuckE was close, what you need to do is change config.autoload_paths to

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

The following works for me

  • create directory app/lib/my_module
  • create file in there called my_module.rb

Contents of file:

module MyModule
  class MyClass
    def self.hello
      puts "Hello"
    end
  end
end
  • ensure config.autoload_paths is as noted above
  • run rails console

Output:

[tharrison@mbpro:~/Sites/test] rails c
Loading development environment (Rails 3.2.9)
1.9.3-p194 :001 > include MyModule
 => Object 
1.9.3-p194 :002 > MyClass.hello
Hello
 => nil 

I haven't tried this from the app, but cannot see why it would be any different than running from the rails console.

Oh, and credit where credit is due: got this from Best way to load module/class from lib folder in Rails 3?

Upvotes: 1

ChuckE
ChuckE

Reputation: 5688

instead of this:

config.autoload_paths += %W(#{config.root}/lib)

try this:

config.autoload_paths += Dir["#{config.root}/lib"]

Upvotes: 0

Related Questions