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 = false
to
true
it would work so I figured it had something to do with rails being unable to to unload or reload classes or constants. After some debugging I found out that the problem was in my custom helper file:
include 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

Singleton
class which lets you instantiate one instance of the class, preventing loading of unloadable classes, making sure there is only one instance of the class.

My 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)

« Back to posts Write a new comment

Feed-icon 0 Comments

Textilized formatting

How to use the text area
_a phrase_ a phrase
*a phrase* a phrase
_*a phrase*_ a phrase
"Link":http://link.com Example link
Complete reference