我需要在Rails中为嵌套模块类创建文件夹层次结构吗 [英] Do I need to create folder hierarchy for nested module class in Rails

查看:75
本文介绍了我需要在Rails中为嵌套模块类创建文件夹层次结构吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a scenario where I just need to inherite the classes in my subclass, there is not single line of code. Just due to STI I need to create it.

Ex:

Ex:

|-- 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

问题和情况:

Question and scenario:

我有很多像Ax1这样的文件,它们需要层次结构,但除继承外不包含任何内容.因此,一种方法是创建所有(不必要的:()文件夹,然后按照Rails约定将文件放入其中.

I have lots of files like Ax1 which needs hierarchy but that doesn't contains anything except inheritance. So one way is to create all (unnecessary :( ) folders and put the file inside it as per Rails conventions.

由于我有许多文件,因此我希望将其与具有继承关系的所有类放入一个文件中(但根据Rails约定,单个类应位于具有相同名称的单个文件中).

And as I have many files so I want it to put in single file with all classes with inheritance (but as per Rails conventions, single class should be in single file with same name).

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

Is there any way to achieve this?

推荐答案

Rails延迟加载代码,因此直到需要时才读取类或模块定义.它将首先寻找顶级常量.因此,如果定义A::A1::Special::A2::Ax1,它将首先在顶层检查a.rb,然后再移至a1.rb.如果它在a.rb中找到类似于class A::A1::Special::A2::Ax1; end的定义,则会引发循环依赖性,因为它将首先一直为该顶级A寻找定义,一遍又一遍地回到a.rb.而且,如果您的类是在某个随机命名的文件中定义的,则将永远找不到它们.只需确保将它们放入具有有意义名称的文件中,然后分别声明每个模块即可.

Rails lazy loads your code, so a class or module definition is not read until it is needed. It will look for the top-level constant first. So if you define A::A1::Special::A2::Ax1 it first checks for a.rb at the top level, before it moves on to a1.rb. If it finds a definition like this class A::A1::Special::A2::Ax1; end in a.rb it will raise a circular dependency because it will keep looking for a definition for that top level A first, going back to a.rb over and over again. And if your classes are defined in some randomly named file, they'll never be found. Just make sure you're putting them in files with names that make sense, and you're declaring each module separately.

这应该有效:

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

这不会

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

这也不会

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

这篇关于我需要在Rails中为嵌套模块类创建文件夹层次结构吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆