在rails中,在哪里放置一个根据当前日期变化的常量(变量?)?
我有一个严重依赖日期的应用程序。根据当前日期设置这些日期需要进行相当昂贵的计算。就每个请求而言,这些日期是恒定的——它们一旦创建就不会改变——但它们在一周内确实会发生变化。这些日期用于控制器和模型。
我的问题是这样的:
- 如果日期每天都没有改变,我可以在配置/初始化程序中设置它们。但是,如果我使用 before_filter 在 applicationController 中设置日期,则仅在服务器重新启动时评估初始值设定项
- ,这些日期对我的模型不可用
有什么想法吗?我看这一切都是错的吗?谢谢。
I have an app that heavily relies on dates. There is a moderately expensive calculation that is needed to set these dates, based on the current date. As far as each request is concerned, these dates are constants -- they don't change once created -- but they do change throughout the week. The dates are used in both controllers and models.
My problem is this:
- if the dates didn't change each day, I could set them in config/initializers. But initializers are only evaluated when the server restarts
- if i set the dates in applicationController using before_filter, the dates aren't available to my models
Any ideas? Am I looking at this all wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是:创建一个单例类,当请求实例时,它会检查日期。从我的头顶上下来,
One way is: make a singleton class which, when asked for an instance, checks the date. Off top of my head,
我认为这里可以使用Rails缓存。请查看此处和此处了解更多详细信息和示例。
基本上,您可以写入缓存:
并读取:
您可以在整个 Rails 应用程序(模型、视图、控制器……)中使用它。
您可以在缓存中存储任何对象。默认缓存使用内存并且可用于单个 Rails 实例,但是您可以使用不同的缓存存储方法。
I think that here you can use Rails caching. Look here and here for more details and examples.
Basicaly, you can write to cache:
and read:
You can use it in whole Rails application (models, views, controllers, ...).
You can store any object in cache. Default caching uses memory and is availble for single Rails instance, however you can use different cache storing method.