开发者

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.r开发者_Python百科b 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?


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.


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.


The issue is twofold.

  1. You need to use the outer Foo scope to define BarWoo
  2. You have defined hello as an instance method, then tried to call it on the class.

Define your method using def self.hello instead of def hello

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


You can also do

module Foo::Barwoo; end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜