Sha256: 1f71d0f96dacad7d0ea13b5cabdd6086d7db66ffd0e21cf892b4ebe25f57e668

Contents?: true

Size: 1.99 KB

Versions: 11

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

11 entries across 11 versions & 1 rubygems

Version Path
intranet-core-2.2.0 lib/intranet/core/haml_wrapper.rb
intranet-core-2.1.4 lib/intranet/core/haml_wrapper.rb
intranet-core-2.1.2 lib/intranet/core/haml_wrapper.rb
intranet-core-2.1.1 lib/intranet/core/haml_wrapper.rb
intranet-core-2.1.0 lib/intranet/core/haml_wrapper.rb
intranet-core-2.0.0 lib/intranet/core/haml_wrapper.rb
intranet-core-1.2.0 lib/intranet/core/haml_wrapper.rb
intranet-core-1.1.1 lib/intranet/core/haml_wrapper.rb
intranet-core-1.0.2 lib/intranet/core/haml_wrapper.rb
intranet-core-1.0.1 lib/intranet/core/haml_wrapper.rb
intranet-core-1.0.0 lib/intranet/core/haml_wrapper.rb