0

我有一个场景,我只需要继承我的子类中的类,没有单行代码。只是由于 STI,我需要创建它。

前任:

|-- app
|   |-- models
|   |   |-- a
|   |   |   |-- a1
|   |   |   |   |-- special
|   |   |   |   |   |-- a2
|   |   |   |   |   |   *-- ax1.rb #(A::A1::Special::A2::Ax1 < A::A1::A2::Ax)
|   |   |   |   |-- a2
|   |   |   |   |   *-- ax.rb
|   |   |-- b
|   |   |   |-- b1
|   |   |   |   |-- b2
|   |   |   |   |   *-- bx.rb #(B::B1::B2::Bx)
|   |   |-- c
|   |   `-- concerns

问题和场景:

我有很多Ax1需要层次结构的文件,但除了继承之外什么都不包含。因此,一种方法是创建所有(不必要的 :( )文件夹并按照 Rails 约定将文件放入其中。

而且由于我有很多文件,所以我希望它与所有具有继承的类一起放入单个文件中(但根据 Rails 约定,单个类应该放在同名的单个文件中)。

有什么办法可以做到这一点?

4

2 回答 2

0

And as I have many files so I want it to put in single file with all classes with inheritance

You can't do this without breaking "convention over configuration". But if you're willing to violate that, it's quite easy. Just put all your classes in one file, say, app/models/my_classes.rb and then just make sure that the file is loaded before you need any class from it.

One way of doing this is create an initializer

# config/initializers/load_common_classes.rb
require 'my_classes'
于 2017-08-02T07:51:14.513 回答
0

Rails 会延迟加载您的代码,因此在需要之前不会读取类或模块定义。它将首先查找顶级常量。因此,如果您定义它首先在顶层A::A1::Special::A2::Ax1检查,然后再移动到. 如果它在其中找到这样的定义,它将引发循环依赖,因为它会首先继续寻找该顶层的定义,然后一遍又一遍地返回。如果你的类是在一些随机命名的文件中定义的,它们将永远不会被发现。只需确保将它们放入名称合理的文件中,并且分别声明每个模块。a.rba1.rbclass A::A1::Special::A2::Ax1; enda.rbAa.rb

这应该有效:

app/models/a.rb

class A
  class A1 < A
    class Special < A1
      class A2 < Special
        class Ax1 < A2
      end
    end
  end
end

这不会

app/models/a.rb

class A::A1::Special::A2::Ax1
end

这也不会

app/models/inherited_classes.rb

class A
  class A1 < A
    class Special < A1
      class A2 < Special
        class Ax1 < A2
      end
    end
  end
end
于 2017-08-02T07:56:45.993 回答