简体   繁体   中英

rails class in folder and module inclusion

I have a class Bar in a folder "models/Foo/" called:

class Foo::Bar

So Bar is in module Foo.

But if I make a file to define module Foo like this:

module Foo
  def baz
  end
end

method baz is undefined if I try:

Foo::Bar.new.baz

Why? how it works? How I have to?

The point is, Rails doesn't necessary requires all the files in the project. Yes, it is true - you can reopen module in Ruby, however you still need to load it somehow.

There's also another mistake you've made. Even if you define a class inside of a module, that class won't have module's methods. In order to add module's functionality to class, you need to include or extend class with that module.

Here's a couple of links you would find useful:

  1. Ruby Tutorial: Modules - quite simple tutorial about modules.
  2. Rails autoloading — how it works, and when it doesn't - it will help you to understand how and when Rails loads classes.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM