从架构的角度来看,Rails 应用程序中的模型是否应该能够在 after_initialize 函数中设置自己的用户关联?
让我们假设以下结构:
class Question < ActiveRecord::Base
after_initialize :set_defaults
belongs_to :user
...
private
def :set_defaults
self.user = SomeAuth.current_user
end
end
class User < ActiveRecord::Base
has_many :questions
...
end
此外,让我们假设 SomeAuth
是某种黑盒魔法身份验证方案。 我们可以将其视为 Devise 或 Authlogic (或在此处插入您最喜欢的 ruby 身份验证解决方案)。
在这些假设下,让 Question
在初始化后设置自己的 user
属性是否是一种反模式(出于所有意图和目的,在 Question.new< /code> 被调用,即在
after_initialize
宏中)?
Let us assume the following structure:
class Question < ActiveRecord::Base
after_initialize :set_defaults
belongs_to :user
...
private
def :set_defaults
self.user = SomeAuth.current_user
end
end
class User < ActiveRecord::Base
has_many :questions
...
end
Further, let us assume that SomeAuth
is some black-box magic authentication scheme.
We can think of that as Devise or Authlogic (or insert your favorite ruby authentication solution here).
Under those assumptions, is it an anti-pattern to have a Question
set its own user
attribute after initialization (for all intents and purposes, after Question.new
is called, i.e. in an after_initialize
macro)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不想从绝对角度将其归类为好或坏模式。
如果您的系统只有一个 RoR 应用程序,那么这似乎是一个很好的模式。您使用框架提供的机制,因此无需创建额外的代码并保持非常简单。您的域对象与您的身份验证方案绑定在一起,但在这个简单的上下文中它可能是有益的。
如果您的系统是许多不同应用程序的集合,并且您希望在它们之间重用域模型,那么您可能需要分离域和身份验证概念。某些子系统可能不关心身份验证问题(例如某种类型的批处理)。在这种情况下,域和身份验证(及其加载方式)之间的显式关系可能是一种反模式。
I wouldn't want to classify it as a good or bad pattern in absolute terms.
If your system is only one RoR application, then it seems like a good pattern. You use a mechanism provided by a framework thus not creating extra code and keeping it pretty simple. Your domain object is tied to your auth scheme, but in this simple context it may be beneficial.
If your system is collection of many distinct applications, and you want to reuse a domain model between them, then you might want to divorce your domain and auth concepts. Some subsystems may not care about auth concerns (like batch processing of a certain kind). In this context an explicit relationship between domain and auth (and the way it gets loaded) might be an anti-pattern.