Search code examples
rubyhamlguard

Passing 'require' to haml guard


Manually compiling haml to html with requirement of external file is performed like so

haml --require .\stuff.rb  --require .\const.rb .\pages\exit.haml .\pages\exit.html

However, I wanted to switch to haml guard. Unfortunately I am unable to find correct flag to pass for it to work. I need something along the lines of:

guard :haml, haml_options: {require: './stuff.rb ./const.rb'}  do
  watch(/^.+(\.haml)$/)
end

The result:

14:19:19 - ERROR - HAML compilation of pages/exit.haml failed! [#] Error: undefined method `html_safe' for nil:NilClass

which shows that neither the method nor constants were included.

Any ideas?

edit: I'm using Ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32] (Win10), Haml 4.0.7.

Minimized example:

test.haml

!!!
%html
    %header
    %body
        %p
            =$BT_OK.html_safe

const.rb

$BT_OK      = "
".html_safe

helpers.rb

class String
  def html_safe?
    defined?(@html_safe) && @html_safe
  end

  def html_safe
    @html_safe = true
    self
  end
end

require 'haml/helpers/xss_mods'
module Haml::Helpers
  include Haml::Helpers::XssMods
end

Output using command line haml .\debug\test.haml .\debug\test.html -r .\const.rb -r .\helpers.rb

<!DOCTYPE html>
<html>
  <header></header>
  <body>
    <p>
      &#13;
    </p>
  </body>
</html>

Error when using matt's solution:

08:02:06 - ERROR - Invalid Guardfile, original error is:
> [#]
> [#] undefined method `html_escape' for module `Haml::Helpers',
> [#] backtrace:
> [#]   (dsl)> C
> [#]   (dsl)> C
> [#]   (dsl)> C
> [#]   (dsl)> C

Solution

  • guard-haml runs Haml “in process”, so in order to have those files available in your Haml script you need to require them in your Guardfile. You’ll also need to require Haml first too, since your helpers refer to some on Haml’s modules:

    require 'haml'
    require './helpers'
    require './const'
    guard :haml do
      watch(/^.+(\.haml)$/)
    end