Module in Rails

Hi,
I want to use module in Rails 3
I have module in /lib directory.

file name: my_module.rb
Code of Module:

module MyModule
def self.my_method
loop do
puts “I am started!!!”
sleep 2
end
end
end

Now, I want to use this module in my rb file resides in app_root/daemon
directory named myserver.rb

How can i use that?

On Thursday, May 19, 2011 5:15:29 AM UTC-6, News A. wrote:

Hi,
I want to use module in Rails 3
I have module in /lib directory.

I’m going to assume by /lib you mean RAILS_ROOT/lib …

  end
end

end

Now, I want to use this module in my rb file resides in app_root/daemon
directory named myserver.rb

How can i use that?

I’ll assume app_root == RAILS_ROOT. So, you created a “daemon” directory
in
the root of your rails app then and placed myserver.rb in it.

Okay, if you’ll be running it manually (not in the context of rails via
rails runner) then your options are:

  1. relative path for require statement in myserver.rb: require
    ‘…/lib/my_module’
  2. an “expand_path”-style relative require statement: require
    File.expand_path(’…/…/lib/my_module’, FILE)
  3. update the load path then require:
    $:.unshift(File.expand_path(’…/…/lib’, FILE) ; require ‘my_module’
  4. … many many variations on the above.

If you are running by using “rails runner daemon/myserver.rb” then the
RAILS_ROOT/lib directory should already be in your load path. You can
just:
require ‘my_module’ and be fine.