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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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)
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.
So if I have lib/elemens/helinium.rb I don't need to require the file. Thanks for your reply
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.
no worries, maybe this is something for a new question? Feel free to accept the answer if it solved your problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.