Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 2.3.5: How does one access code inside of lib/directory/file.rb?

I created a file so I can share a method amongst many models in lib/foo/bar_woo.rb. Inside of bar_woo.rb I defined the following:

module BarWoo
  def hello
   puts "hello"
  end
end

Then in my model I'm doing something like:

  def MyModel < ActiveRecord::Base
      include Foo::BarWoo
      def some_method
         Foo::BarWoo.hello
      end
  end

The interpreter is complaining that it expected bar_woo.rb to define Foo::BarWoo.

The Agile Web Development with Rails book states that if files contain classes or modules and the files are named using the lowercase form of the class or module name, then Rails will load the file automatically. I didn't require it because of this.

What is the correct way to define the code and what is the right way to call it in my model?

like image 996
randombits Avatar asked May 08 '10 23:05

randombits


2 Answers

You might want to try:

module Foo
  module BarWoo
    def hello
      puts "hello"
    end
  end
end

Also for calling you won't call it with Foo::BarWhoo.hello - that would have to make it a class method. However includeing the module should enable you to call it with just hello.

like image 179
Jakub Hampl Avatar answered Nov 03 '22 08:11

Jakub Hampl


Files in subdirectories of /lib are not automatically require'd by default. The cleanest way to handle this is to add a new initializer under config/initializers that loads your library module for you.

In: config/initializers/load_my_libraries.rb Pick whatever name you want.

require(File.join(RAILS_ROOT, "lib", "foo", "bar_woo"))

Once it has been require'd, you should be able to include it at will.

like image 24
jdl Avatar answered Nov 03 '22 08:11

jdl