Sha256: f1721cb1982c383805a21f1660697461bb971726eb79ae15b3d45504ad9d64d0

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

require "dry/core/cache"
require "dry/core/equalizer"
require_relative "errors"
require_relative "tilt"

module Hanami
  class View
    # @api private
    class Renderer
      PARTIAL_PREFIX = "_"
      PATH_DELIMITER = "/"

      extend Dry::Core::Cache

      include Dry::Equalizer(:paths, :format, :engine_mapping, :options)

      attr_reader :paths, :format, :engine_mapping, :options

      def initialize(paths, format:, engine_mapping: nil, **options)
        @paths = paths
        @format = format
        @engine_mapping = engine_mapping || {}
        @options = options
      end

      def template(name, scope, **lookup_options, &block)
        path = lookup(name, **lookup_options)

        if path
          render(path, scope, &block)
        else
          raise TemplateNotFoundError.new(name, paths)
        end
      end

      def partial(name, scope, &block)
        template(
          name_for_partial(name),
          scope,
          child_dirs: %w[shared],
          parent_dir: true,
          &block
        )
      end

      def render(path, scope, &block)
        tilt(path).render(scope, &block)
      end

      def chdir(dirname)
        new_paths = paths.map { |path| path.chdir(dirname) }

        self.class.new(new_paths, format: format, **options)
      end

      private

      def lookup(name, **options)
        paths.inject(nil) { |_, path|
          result = path.lookup(name, format, **options)
          break result if result
        }
      end

      def name_for_partial(name)
        name_segments = name.to_s.split(PATH_DELIMITER)
        name_segments[0..-2].push("#{PARTIAL_PREFIX}#{name_segments[-1]}").join(PATH_DELIMITER)
      end

      def tilt(path)
        fetch_or_store(:engine, path, engine_mapping, options) {
          Tilt[path, engine_mapping, **options]
        }
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
hanami-view-2.0.0.alpha7 lib/hanami/view/renderer.rb
hanami-view-2.0.0.alpha6 lib/hanami/view/renderer.rb
hanami-view-2.0.0.alpha5 lib/hanami/view/renderer.rb
hanami-view-2.0.0.alpha3 lib/hanami/view/renderer.rb
hanami-view-2.0.0.alpha2 lib/hanami/view/renderer.rb