Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a HAML custom filter?

Tags:

haml

I have written a simple custom filter in HAML but I cannot get my Rails app to find it.

The filter looks like this:

# lib/haml/filters/gfmarkdown.rb
module Haml::Filters::Gfmarkdown
  include Haml::Filters::Base

  # copied from Haml::Filters::Markdown
  lazy_require 'rdiscount', 'peg_markdown', 'maruku', 'bluecloth'

  def render(text)
    # copied from Haml::Filters::Markdown
    engine = case @required
             when 'rdiscount'
               ::RDiscount
             when 'peg_markdown'
               ::PEGMarkdown
             when 'maruku'
               ::Maruku
             when 'bluecloth'
               ::BlueCloth
             end
    engine.new(gfm text).to_html  # gfm method defined elsewhere
  end
end

In my views, I try to use this filter like so:

:gfmarkdown
  #{comment.body}

But I get this error message: Filter "gfmarkdown" is not defined.

Any ideas how I can get my Rails app to pick up my filter?

Versions: Rails 2.3.4, Haml 2.2.15.

like image 507
Andy Stewart Avatar asked Dec 17 '09 13:12

Andy Stewart


1 Answers

I have found the solution: add an initializer which requires the filter.

# config/initializers/gfmarkdown.rb
require 'haml/filters/gfmarkdown'

I had thought that modules in lib/ were auto-required if the module hierarchy matched the file path. Oh well ;)

like image 68
Andy Stewart Avatar answered Nov 15 '22 10:11

Andy Stewart