对 Rails 初始值设定项中的夹具数据的依赖

发布于 2024-07-13 16:09:59 字数 456 浏览 5 评论 0原文

我有一个初始化程序,它设置在整个应用程序中使用的默认值。 该值是一个 ActiveRecord 模型,我本质上是在应用程序的生命周期内缓存它:

@@default_region = Region.find_by_uri("whistler")

该记录保证位于数据库中:它是其他模型引用的夹具数据。 这工作得很好,除了在每次测试运行之前都会清除数据库的测试环境中。 (我在边缘导轨上运行,我认为这是最近的行为:我过去能够手动插入数据并在测试运行之间保留它。)我的 regions.yml 中也有记录固定装置文件,但固定装置只有在 Rails 初始化程序完成后才会加载。

处理对夹具数据的这种依赖性的正确方法是什么? 或者有更好的方法来构建这个吗? 我宁愿不使用 before_filter,因为在每个请求上重新加载它是没有意义的:除非在不同的部署上,否则它不会改变。

I have an initializer which sets a default that is used throughout the app. The value is an ActiveRecord model, I'm essentially caching it for the lifetime of the app:

@@default_region = Region.find_by_uri("whistler")

The record is guaranteed to be in the database: it's fixture data which is referenced by other models. This works fine, except in the test environment where the database is purged before every test run. (I'm running on edge rails and I think that's recent behavior: I used to be able to insert the data manually and keep it between test runs.) I also have the record in my regions.yml fixture file, but fixtures aren't loaded until after the rails initializer is done.

What's the right way to deal with such a dependency on fixture data? Or is there a better way to structure this? I'd rather not use a before_filter because there's no sense reloading this on each request: it will not change except on a different deployment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花桑 2024-07-20 16:09:59

我将这样的内容放在region.rb中:

def self.default_region
  @@default_region ||= Region.find_by_uri("whistler")
end

然后您可以在任何需要的地方将其作为Region.default_region访问,并且仅查找一次(第一次调用时),然后固定装置将就位。

I'd put something like this in region.rb:

def self.default_region
  @@default_region ||= Region.find_by_uri("whistler")
end

Then you can access it as Region.default_region wherever you need it, and it's only looked up once - the first time it's called - and by then the fixtures will be in place.

晚雾 2024-07-20 16:09:59

对 Ruby 或 Rails 不太熟悉...但是为什么不尝试“延迟加载”场景呢? 基本上,有一个全局函数来检查数据是否已加载,如果没有,则从数据库中获取数据,然后缓存它。 如果它已经被缓存,则返回它。

这样,在第一次调用该函数之前您不会尝试访问数据库,并且那时所有内容都应该已初始化。

Not really familiar with Ruby or Rails... but why don't you try a "lazy-loading" scenario? Basically, have a global function that would check to see if the data was loaded, and if not, grab it from the database, then cache it. And if it was already cached, just return it.

That way, you won't be attempting to hit the database until that function is called for the first time and everything should be initialized by then.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文