Search code examples
ruby-on-railsrefactoringhamlview-helpers

Rails: Is it possible to write view helpers with HAML syntax?


During refactoring it would be quite handy just to copy part of HAML template and paste it to helper's code. Currently in such cases 1) I have to rewrite that part of view from scratch 2) I have to use that verbose syntax like content_tag or haml_tag.

I know that it's possible to define partials with HAML systax that will serve as helper. Though 1) as for me it's inconvinient to create a separate file for each small tiny function 2) invocation syntax for partial is quite verbose.

Ideally i'd like my *_helper class to look like this:

- def some_helper(*its_args)
  .some_class
    = some_ruby_expression
  %some_tag#some_id
    - another_expression do
      etc

or at least like this:

define_haml_helper :some_helper, [:arg1, :arg2], %{
  .some_class
    = some_ruby_expression
  %some_tag#some_id
    - another_expression do
      etc
}

Is there a plugin that solves my issue?

Alternatively, maybe you can describe how do you refactor HAML snippets to reusable elements (helpers/functions/partials/builders/etc)?


Solution

  • From the reference:

    def render_haml(code)
        engine = Haml::Engine.new(code)
        engine.render
    end
    

    This initiates a new Haml engine and renders it.