Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top