How to implement a singleton model

后端 未结 13 1361
余生分开走
余生分开走 2020-12-24 12:36

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

13条回答
  •  长发绾君心
    2020-12-24 12:41

    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).

    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:

    1. undef the initialize/new method
    2. define only self.* methods that way it is not possible for you to maintain a state

提交回复
热议问题