Sha256: c6f45f27735326bf2ebfb514d0364fb653df8ef9de242be13e72bbb216ff1e7c

Contents?: true

Size: 1.81 KB

Versions: 6

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

require_relative "errors"

module Hanami
  # Calls `configure_for_slice(slice)` on the extended class whenever it is first
  # subclassed within a module namespace corresponding to a slice.
  #
  # @example
  #   class BaseClass
  #     extend Hanami::SliceConfigurable
  #   end
  #
  #   # slices/main/lib/my_class.rb
  #   module Main
  #     class MyClass < BaseClass
  #       # Will be called with `Main::Slice`
  #       def self.configure_for_slice(slice)
  #         # ...
  #       end
  #     end
  #   end
  #
  # @api private
  # @since 2.0.0
  module SliceConfigurable
    class << self
      def extended(klass)
        slice_for = method(:slice_for)

        inherited_mod = Module.new do
          define_method(:inherited) do |subclass|
            unless Hanami.app?
              raise ComponentLoadError, "Class #{klass} must be defined within an Hanami app"
            end

            super(subclass)

            subclass.instance_variable_set(:@configured_for_slices, configured_for_slices.dup)

            slice = slice_for.(subclass)
            return unless slice

            unless subclass.configured_for_slice?(slice)
              subclass.configure_for_slice(slice)
              subclass.configured_for_slices << slice # WIP
            end
          end
        end

        klass.singleton_class.prepend(inherited_mod)
      end

      private

      def slice_for(klass)
        return unless klass.name

        slices = Hanami.app.slices.with_nested + [Hanami.app]

        slices.detect { |slice| klass.name.include?(slice.namespace.to_s) }
      end
    end

    def configure_for_slice(slice); end

    def configured_for_slice?(slice)
      configured_for_slices.include?(slice)
    end

    def configured_for_slices
      @configured_for_slices ||= []
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
hanami-2.0.3 lib/hanami/slice_configurable.rb
hanami-2.0.2 lib/hanami/slice_configurable.rb
hanami-2.0.1 lib/hanami/slice_configurable.rb
hanami-2.0.0 lib/hanami/slice_configurable.rb
hanami-2.0.0.rc1 lib/hanami/slice_configurable.rb
hanami-2.0.0.beta4 lib/hanami/slice_configurable.rb