philipjkim
philipjkim

Reputation: 4139

How to use alias_method in Haml to escape html?

What I want to do is using an alias method (defined in a ruby file) in Haml view.

I defined an alias method like following:

require 'sinatra'
require 'sinatra/base'
require 'data_mapper'
require 'haml'

helpers do
  include Haml::Helpers
  alias_method :h, :html_escape
end

class App < Sinatra::Base

  use Rack::MethodOverride

  # ...

end

Then I used method h() in a Haml view like following:

- @notes.each do |note|
  %article{:class => note.complete? && "complete"}
    %p
      =h note.content

But I got an error when I opened the page:

NoMethodError - undefined method `h' for #:

...

When I use Haml::Helpers.html_escape() directly on the haml file, there's no problem:

%p
  = Haml::Helpers.html_escape note.content

How can I use my alias method in haml files without errors?

Thanks for any advices or corrections to this questions.

Upvotes: 0

Views: 548

Answers (1)

Joshua Cheek
Joshua Cheek

Reputation: 31726

Your helpers are getting defined in Application. Instead define them in your class like this:

class App < Sinatra::Base
  helpers do
    include Haml::Helpers
    alias_method :h, :html_escape
  end

  # ...

end

or in Base like this:

Sinatra::Base.helpers do
  include Haml::Helpers
  alias_method :h, :html_escape                                                                                                                    
end

Upvotes: 4

Related Questions