Using Helper Methods in Your Model? Yes.

At one point I found myself wanting to use Rails' auto_link helper in a to_html method on one of my models. If you need this functionality, here's how you would do it:

class Formatter

  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::TextHelper

  def initialize(content)
    @content = content
  end

  def to_html
    auto_link(@content)
  end

end

I had to include TagHelper to satisfy dependencies for the h() and content_tag() methods. Though I ended up writing a custom formatter class instead in this case, this is still a useful approach.

blog comments powered by Disqus