【发布时间】:2013-07-12 21:50:40
【问题描述】:
在我正在处理的一个 Ruby 项目中,我将 ActiveRecord 风格的 MVC 功能添加到具有类似于以下混合架构的模型类中:
module Model
# Classes that mixin this module gain ActiveRecord-style class methods
# like Model.all, Model.first, Model.last et al.
#
# Throughout this module, @@database_bridge will contain a reference to a
# database ORM bridge, that does the dirty implementation of these methods.
def all
# Implementation stuff here, using @@database_bridge as appropriate
end
def first
...
end
# et al
end
class ExampleModel
extend Model
# Model-specific implementation goes here...
end
调用e = ExampleModel.first 会将数据库中的第一个ExampleModel 分配给e。
我想在运行时使用依赖注入来设置@@database_bridge,这样每个包含extend Model 的类都使用相同的指定ORM 对象。
我该怎么做?
如果我可以编写某种辅助方法来按需设置该类变量,那就太好了。
【问题讨论】:
-
如果有人认为我最好从基本的“模型”类继承东西,那真的不适合我的类层次结构。该框架的核心不是 MVC,它只是使用 MVC 样式的类方法作为从数据库中提取内容的一种优雅方式。
标签: ruby dependency-injection mixins class-variables