Sha256: 7b7443c4ddf40749a2058f83035ced736e4fc9f1d139120f69e868f0c76b6c2e

Contents?: true

Size: 1.85 KB

Versions: 22

Compression:

Stored size: 1.85 KB

Contents

require 'hanami/view/rendering/null_template'
require 'hanami/view/rendering/templates_finder'

module Hanami
  module View
    module Rendering
      # Holds the references of all the registered layouts.
      # As now the registry is unique at the level of the framework.
      #
      # @api private
      # @since 0.1.0
      #
      # @see Hanami::Layout::ClassMethods#registry
      class LayoutRegistry
        # Initialize the registry
        #
        # @param view [Class] the view
        #
        # @api private
        # @since 0.1.0
        def initialize(view)
          @registry = {}
          @view = view
          prepare!
        end

        # Returns the layout for the given context.
        #
        # @param context [Hash] the rendering context
        # @option context [Symbol] :format the requested format
        #
        # @return [Hanami::Layout, Hanami::View::Rendering::NullTemplate]
        #   the layout associated with the given context or a `NullTemplate` if
        #   it can't be found.
        #
        # @raise [Hanami::View::MissingFormatError] if the given context doesn't
        #   have the :format key
        #
        # @api private
        # @since 0.1.0
        def resolve(context)
          @registry.fetch(format(context)) { NullTemplate.new }
        end

        protected
        # @api private
        # @since 0.1.0
        def prepare!
          templates.each do |template|
            @registry.merge! template.format => template
          end
          @registry.any? or raise MissingTemplateLayoutError.new(@view)
        end

        # @api private
        # @since 0.1.0
        def templates
          TemplatesFinder.new(@view).find
        end

        # @api private
        # @since 0.1.0
        def format(context)
          context.fetch(:format) { raise MissingFormatError }
        end
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
hanami-view-1.0.0.rc1 lib/hanami/view/rendering/layout_registry.rb
hanami-view-1.0.0.beta2 lib/hanami/view/rendering/layout_registry.rb