Sha256: f8c0f856044395d1b4423762a226a529642a99916747bb4e069cea7d8a851b67

Contents?: true

Size: 1.99 KB

Versions: 9

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require 'haml'

module Intranet
  class Core
    # Wrapps the Haml engine from the Haml gem.
    # This module has to be included in any class wanting to generate a HTML/XML
    # from HAML templates.
    module HamlWrapper
      # @!visibility protected
      # The default path to the HAML files.
      DEFAULT_HAML_DIR = File.join(__dir__, '..', 'resources', 'haml')

      class << self
        # @!visibility protected
        # Haml load path (not to be modified directly)
        attr_accessor :load_path
      end

      # @!visibility protected
      # Initializes HAML templates load path.
      # @param default_haml_dir [String] The path to the directory containing default HAML
      #                                  templates.
      def self.initialize(default_haml_dir = DEFAULT_HAML_DIR)
        self.load_path = [default_haml_dir]
      end

      # @!visibility protected
      # Adds a HAML templates directory.
      # @param dir [String] The path to the directory to add.
      def self.add_path(dir)
        HamlWrapper.load_path.unshift(dir) # prepend load_path
      end

      # Generate the HTML/XML from a given HAML template.
      # @param template [String] The name of the HAML template to use.
      # @param content [Hash] The additional content required to generate the HTML/XML.
      # @return [String] The HTML/XML content.
      def to_markup(template, content = {})
        fd = File.read(find_template(template))
        Haml::Engine.new(fd, escape_html: false).render(self, content)
      rescue Errno::ENOENT # template file does not exists
        ''
      end

      private

      # Look for an HAML template in the registered paths.
      # @return [String] The path to the template if it exists, an empty string otherwise.
      def find_template(template)
        HamlWrapper.load_path.each do |dir|
          candidate = File.join(dir, "#{template}.haml")
          return candidate if File.exist?(candidate)
        end
        ''
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
intranet-core-2.4.5 lib/intranet/core/haml_wrapper.rb
intranet-core-2.4.4 lib/intranet/core/haml_wrapper.rb
intranet-core-2.4.3 lib/intranet/core/haml_wrapper.rb
intranet-core-2.4.1 lib/intranet/core/haml_wrapper.rb
intranet-core-2.4.0 lib/intranet/core/haml_wrapper.rb
intranet-core-2.3.3 lib/intranet/core/haml_wrapper.rb
intranet-core-2.3.2 lib/intranet/core/haml_wrapper.rb
intranet-core-2.3.1 lib/intranet/core/haml_wrapper.rb
intranet-core-2.3.0 lib/intranet/core/haml_wrapper.rb