This post originated from an RSS feed registered with Ruby Buzz
by Jonathan Weiss.
Original Post: Rails 1.2 and reloading classes
Feed Title: BlogFish
Feed URL: http://blog.innerewut.de/feed/atom.xml
Feed Description: Weblog by Jonathan Weiss about Unix, BSD, security, Programming in Ruby, Ruby on Rails and Agile Development.
With Rails 1.2 on the edge of being released I thought I give it a go with one of my projects. Apart from all the depreciation warnings that are very easy and fast to fix I stumbled over one issue.
With Rails 1.2 the dependencies and reloading code was significantly changed. This can result in loading problems with your classes in lib/ when they end up being reloaded when you do not want them to. In my case I had a static helper class (as Java folks would call it) under lib/. This class offers some class-methods that do general purpose stuff (like Math::sqrt). Until now nothing new and still working.
My problem was that I used class-methods to set some class attributes (aka @@option) on the class in config/environment.rb to do some configuration (like telling it about a .so and running mode). On the first request everything worked like a charm any further request always broke because the class was not configured. It seems like it gets reloaded on every request but the calls in config/environment.rb are of course executed only once.
With the old ways of not reloading classes in lib/ this was fine as the class with its state stayed around after each request. The obvious way to fix this would be to refactor this static class to be used through its instances like
m = Math.new
m.srqt(5)
and do the configuration in the controller call. But this was just not right if you looked at what the class is supposed to do and re-doing the configuration in each request is just wrong. After a quick look through the sources I did not find a way to exclude my class. So I went for the quick and dirty solution.
I created vendor/plugins/my_class and moved my class there. By creating a plugin out of my class I ensure that it is loaded only once. Not nice but works until I find out how to exclude my class from the request reloading chain.