Skip to content

Ruby: Herb ~H Sigil #950

@marcoroth

Description

@marcoroth

Gist: https://gist.github.com/marcoroth/ee2c38ae7018767b9598bdf4f152e6b5

require "herb"

module Herb
  module Sigil
    class Fragment
      def initialize(source)
        @source = source
        @compiled = Herb::Engine.new(@source).src
      end

      def ~@
        eval(@compiled)
      end

      def +@
        @compiled
      end
    end

    def H(source)
      Fragment.new(source)
    end
  end
end

include Herb::Sigil

puts +H(%(
  <div>
    <%= "Hello" %>
  </div>
))

# => "_buf = ::String.new; _buf << '\n  <div>\n    '.freeze; _buf << (\"Hello\").to_s; _buf << '\n  </div>\n'.freeze;\n_buf.to_s\n"

puts ~H(%(
  <div>
    <%= "Hello" %>
  </div>
))

# => "\n  <div>\n    Hello\n  </div>\n"

Inspired by Phoenix LiveView's ~H Sigil

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions