【问题标题】:Module/Class clash trying to namespace models in Rails模块/类冲突试图在 Rails 中命名模型
【发布时间】:2015-05-03 03:25:24
【问题描述】:

由于我的应用现在变得有点大,我正在尝试使用命名空间来帮助更好地组织我的模型。

我创建了一个 app/models/theme.rb 文件,它将作为通往主题子目录中其余主题相关模型的网关。

# app/models directory
theme.rb
theme/compiler.rb
theme/instance.rb
theme/revision.rb

instance.rb 将在哪里开始......

class Theme::Instance < ActiveRecord::Base

end

而theme.rb 就是...

class Theme

  def initialize(args)
    # some stuff here
  end
end

但是每当我使用生成器创建新模型时,它都会尝试覆盖新的 theme.rb,如下所示。

rails g model theme::revision

#new theme.rb

module Theme
  def self.table_name_prefix
    'theme_'
  end
end

我可以摆脱模块并将 def self.table_name_prefix 方法复制到每个类,但这似乎不是很干。我想使用表前缀,因为它使数据库中的事情更加明显。有没有我错过的“正确”的 Rails 方法?

【问题讨论】:

  • 我认为Theme 应该是一个模块,而不是一个类。使用Theme::Instance 语法更有意义。

标签: ruby-on-rails ruby-on-rails-4 namespaces


【解决方案1】:

我想最简单的方法是将 Theme 定义为所有类都扩展的模块

Theme::Instance 暗示 Instance 类包含在 Theme 模块中。

作为替代方案,您可以创建一个 ThemeUtils 模块,其中包含每个类中包含的所有常用方法,例如 /lib 中的插件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2016-12-06
    • 2015-08-03
    • 2010-12-16
    • 2020-06-18
    相关资源
    最近更新 更多