【问题标题】:inject/access methods from a parent module inside a model从模型内的父模块注入/访问方法
【发布时间】:2011-11-24 18:32:38
【问题描述】:

在 Rails 中,我有以下结构

#.../models/A.rb
module A
  def m
  end
end

#.../models/a/B.rb
class A::B < ActiveRecord::Base
end

这会自动将 A 放置为 B 的父级。有没有办法在不修改 B 的情况下执行类似 B.m 的操作?我知道我可以执行类似 B.parent.m 的操作并从那里创建别名,但我必须更改 B。
我希望以某种方式将 A 中存在的代码注入 B,但我不知道这种自动关联是在幕后完成的。 类似的东西

module A
  module C
    def mc
    end
  end
  def placed_as_parent (child) # supposing this is the method called to put this module as a parent 
    super child
    child.include(C) #this is what I would like to do
  end
end

它背后的问题是我有一个模块已经在该文件夹的几个模型之间共享,我想在其中放置一些模型的通用内容,而不必在每个模型中手动包含/扩展一个模块我的模型

[[编辑]]

我的问题不清楚。如果你这样做,在 Rails 3 中

rails generate active_record:model A::B

它会生成文件

#.../models/A.rb
module A
  def self.table_name_prefix
    'a_'
  end
end

#.../models/a/B.rb
class A::B < ActiveRecord::Base
end

如果我打开控制台并输入

A::B.table_name # -> 'a_b'
A::B.table_name_prefix # -> ''
A::B.parent # -> A
A.table_name_prefix # 'a_'

这会自动发生在模型 B 中没有任何包含/扩展。我想要的是在 A 中包含更多内容并从 B 中访问它,而不像前面描述的那样更改 B 上的任何内容。

【问题讨论】:

  • 感谢您澄清这一点。现在我们知道你想要的在 Ruby 语言中是可能的,这只是弄清楚如何做的问题。我们可以阅读 ActiveRecord 的源代码。
  • 当然,我知道我想要的都是可能的!我想知道如何/最好的方法是什么

标签: ruby-on-rails ruby


【解决方案1】:

说实话,我不确定我是否完全理解你的问题,但我还是会试一试。

Module 类中有一个钩子,可让您获取对包含该模块的类的引用。因此,您几乎可以用它做任何事情。

一个例子:

module A  
  # you can change the class' behavior here
  def self.included(klass) 
    puts "included in #{klass}" 
  end
end

然后使用它:

class B
  include A #this causes the included hook in the module to be called
end

这就是你所追求的吗?

【讨论】:

  • 我知道这种方法,但这不是我想要的,因为我必须在 B 中写 'include A'
【解决方案2】:

OP 写道:

它背后的问题是我有一个模块已经在该文件夹的几个模型之间共享,我想在其中放置一些模型的通用内容,而不必在每个模型中手动包含/扩展一个模块我的模型

我会这样做:

module Stuff1
   ...
end

module Stuff2
   ...
end

module StuffIWantInSeveralModels
   include Stuff1, Stuff2
end

class X < ActiveRecord::Base
    include StuffIWantInSeveralModels
end

class Y < ActiveRecord::Base
    include StuffIWantInSeveralModels
end

然后,当您想向多个模型添加新模块时,您只需在一个地方(在 StuffIWantInSeveralModels 模块中)编写“包含”语句。

每个模块都应该在 lib 目录中自己的文件中,文件名与模块名匹配,以便 Rails 自动加载工作(例如 stuff_i_want_in_several_models.rb)。

这能达到你想要的吗?

【讨论】:

  • 是的,它实现了我想要的(我在我的应用程序中使用它),但我正在寻找一种使用rails 的自动模型链接的新方法。
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多