/me@(voip.)?|www./ SamLown.com

Rails: Vanishing singleton class variables in lib

I just spent a good hour or two discovering why my class variables were loosing there values, so I thought I’d share my experiences. The idea is to use a TextFilter class and some filters in the `/lib/text_filter` directory so that the filters are loaded automatically and the TextFilter class contains a list of the available filters. It should be mentioned that the idea is blatantly stolen from develot.

Firstly, it turns out that class variables in ruby are strange beasts. So not wanted to create problems, I used:

class TextFilter
  class << self
    attr_accessor :filters
  end
end

This way self.filters can be used inside the class without problems.

However, this didn’t work. It would work the first time I loaded a page that used the TextFilter.list, but all following uses would bring up an empty list.

The solution to this, is to include require `‘lib/text_filter’` in your `environment.rb` file. My assumption is that Rails includes some funky auto-loading on the `/lib` libraries which causes them to be forgotten when not used.

written by Sam,


No comments yet


Write your comment



HTML will be removed, but Textile formating is permitted. Log in for your comment to be posted without review.