views:

497

answers:

2

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.

+1  A: 

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.

bobwienholt
In the test environment the database gets purged, so there's nothing to lazy-load from the database at this point. I would have to load it into the database from a file if it doesn't exist.
Andrew Vit
I thought you said that the fixtures are loaded after the rails initializer is done. Am I missing something?
bobwienholt
Yes, the test sequence works like this: running `rake test` clears the database; rails initializes (this is where I hit the dependency); then the fixtures are loaded for the test environment.
Andrew Vit
+2  A: 

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.

Sarah Mei
Very good solution... gets rid of the whole dependency. Everything moves to the model eventually!
Andrew Vit