如何实现单例模型 [英] How to implement a singleton model
问题描述
我在 rails 中有一个站点,并且想要进行站点范围的设置.如果发生特定事件,我的应用程序的一部分可以通过短信通知管理员.这是我希望通过站点范围的设置进行配置的功能示例.
I have a site in rails and want to have site-wide settings. One part of my app can notify the admin by SMS if a specific event happens. This is an example of a feature that I want configurable via the site-wide settings.
所以我想我应该有一个设置模型或其他东西.它需要是一个模型,因为我希望能够 has_many :contacts 用于 SMS 通知.
So I was thinking I should have a Setting model or something. It needs to be a model because I want to be able to has_many :contacts for the SMS notification.
问题是设置模型的数据库中只能有一个帖子.所以我在考虑使用单例模型,但这只会阻止创建新对象,对吗?
The problem is that there can only be one post in the database for the settings model. So I was thinking of using a Singleton model but that only prevents new object to be created right?
我是否仍然需要像这样为每个属性创建 getter 和 setter 方法:
Would I still need to create getter and setter methods for each attribute like so:
def self.attribute=(param)
Model.first.attribute = param
end
def self.attribute
Model.first.attribute
end
直接使用 Model.attribute 但总是创建它的一个实例并使用它可能不是最佳实践吗?
Is it perhaps not best-practice to use Model.attribute directly but always create an instance of it and use that?
我应该在这里做什么?
推荐答案
我不确定我是否会为了这种基本需求而浪费数据库/ActiveRecord/Model 开销.这些数据是相对静态的(我假设)并且不需要即时计算(包括数据库查找).
I am not sure I'd waste the database/ActiveRecord/Model overhead for such a basic need. This data is relatively static (I am assuming) and on the fly calculations aren't necessary (including database lookups).
话虽如此,我建议您使用站点范围的设置定义一个 YAML 文件,并定义一个将设置加载到常量中的初始化文件.您几乎不会有那么多不必要的活动部件.
Having said that, I'd recommend you define a YAML file with your site-wide settings and define an initializer file that loads the settings into a constant. You won't have nearly as many of the unnecessary moving parts.
数据没有理由不能只是放在内存中并为您节省大量的复杂性.常量随处可用,它们不需要初始化或实例化.如果将类用作单例绝对至关重要,我建议您做以下两件事:
There is no reason that data couldn't just sit in memory and save you a ton of complexity. Constants are available everywhere, and they don't need to be initialized or instantiated. If its absolutely critical that you utilize a class as a singleton, I'd recommend doing these two things:
- 取消定义初始化/新方法
- 只定义 self.* 方法,这样你就不可能维护状态
这篇关于如何实现单例模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!