Sha256: e554d4e8ac9a6a09203cc25e4caf1c783ef9863ae8effa012eb74d2e06294ead

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

require "dry/core/cache"
require "tilt"

module Dry
  class View
    # @api private
    module Tilt
      extend Dry::Core::Cache

      class << self
        def [](path, mapping, **options)
          ext = File.extname(path).sub(/^./, "").to_sym
          activate_adapter ext

          with_mapping(mapping).new(path, **options)
        end

        def default_mapping
          ::Tilt.default_mapping
        end

        def register_adapter(ext, adapter)
          adapters[ext] = adapter
        end

        def deregister_adapter(ext)
          adapters.delete(ext)
        end

        private

        def adapters
          @adapters ||= {}
        end

        def activate_adapter(ext)
          fetch_or_store(:adapter, ext) {
            adapter = adapters[ext]
            return unless adapter

            *requires, error_message = adapter.requirements

            begin
              requires.each(&method(:require))
            rescue LoadError => e
              raise e, "#{e.message}\n\n#{error_message}"
            end

            adapter.activate
          }
        end

        def with_mapping(mapping)
          fetch_or_store(:mapping, mapping) {
            if mapping.any?
              build_mapping(mapping)
            else
              default_mapping
            end
          }
        end

        def build_mapping(mapping)
          default_mapping.dup.tap do |new_mapping|
            mapping.each do |extension, template_class|
              new_mapping.register template_class, extension
            end
          end
        end
      end
    end
  end
end

require_relative "tilt/erb"
require_relative "tilt/haml"

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-view-0.8.0 lib/dry/view/tilt.rb
dry-view-0.7.1 lib/dry/view/tilt.rb