Vidar
20 December 2009
Custom libraries with rails helpers
After upgrading from Rails 2.3.2 to 2.3.3 through 2.3.5 I had a lot of strange errors in my console, the latest being Read error: and it was really annoying as you might figure. If I set
config.cache_classes = falsetrueinclude ActionView::Helpers module HtmlHelper def self.htmlify(text) html = strip_tags(text) html = auto_link(html, :link => :urls, :href_options => {:target => '_blank'}) html = simple_format(html) return html end end
In this file I am using the built-in helpers in rails to format input from the user into html for the web application. I accessed it statically like this from my model
result = HtmlHelper::htmlify(text)
Rails does not like this even if it works in the console and if not caching classes (aka in production). I don’t know if it’s a bug or if I’m doing it wrong. I googled around and found this guy which led me onto the
SingletonMy helper now looks like this
module HtmlHelper class Transformer include Singleton include ActionView::Helpers def htmlify(text) html = strip_tags(text) html = auto_link(html, :link => :urls, :href_options => {:target => '_blank'}) html = simple_format(html) return html end end end
And I’m calling it like this
result = HtmlHelper::Transformer.instance.htmlify(text)
or of course
helper = HtmlHelper::Transformer.instance result = helper.htmlify(text)