6

I'm working on a Rails (3.2) app and I need to execute some tasks when the app boots.

Since I want to keep the logic in a separate file I have also create lib/helinium.rb that looks like (with dummy run method)

class Helinium
  def self.run
    puts "running ...."
  end
end

And I have created a simple initializer file config/initializers/perform_checks.rb

Helinium.run

And everything seems fine. Now I wish to put the Helinium class within a module so the two files look respectively like

module Elemens
  class Helinium
      def self.run
        puts "running ...."
      end
  end
end

and

Elemens::Helinium.run

but when I try to boot the app I get

uninitialized constant Elemens (NameError)

Am I missing something here? Why the module is not found?

Thanks and have a nice day.

Sig
  • 5,476
  • 10
  • 49
  • 89

1 Answers1

10

explanation

This has something to do how the autoloading works in Rails.

Rails doesn't automatically require everything under /lib. It only auto loads when you try to use a new class name that matches a file name in lib.

You may check this post for more info:
https://stackoverflow.com/a/9819938/1188913

fix

To fix your issue you could

require 'lib/helinium'

OR

put the class into a folder called lib\elemens

Community
  • 1
  • 1
deepflame
  • 928
  • 1
  • 8
  • 19
  • 1
    Thanks I though adding the following line to application.rb would be enough but actually it wasn't. config.autoload_paths += %W(#{config.root}/lib) – Sig Mar 15 '13 at 07:40
  • it really depends on how you name the class inside and where you place it. You can also put the class into an 'elemens' folder to make it work. – deepflame Mar 15 '13 at 07:43
  • So if I have lib/elemens/helinium.rb I don't need to require the file. Thanks for your reply – Sig Mar 15 '13 at 07:46
  • Sorry If I bother you again but is there a way to ensure my initializer is executed as last operation during the boot? I need to know the available models. I call ActiveRecord::Base.descendants but it returns an empty array. Thanks again. – Sig Mar 15 '13 at 08:10
  • no worries, maybe this is something for a new question? Feel free to accept the answer if it solved your problem – deepflame Mar 15 '13 at 10:21