Sha256: 00f3922d2bd33ead2bba2476fd67f3b8945812188f2819fb3cbc370829a24276

Contents?: true

Size: 1.12 KB

Versions: 10

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

require_relative 'context'
require_relative 'initializers/contexts'

module Coactive
  module Initializer
    extend ActiveSupport::Concern
    include Initializers::Contexts

    included do
      class_attribute :context_class
      self.context_class = Context
      attr_reader :context
    end

    def initialize(args = {}, &block)
      @context = self.class.context_class.new(args, &block)
      @context.define_accessors!(self.class._contexts.map(&:name))

      self.class._contexts.each do |var|
        if var.required? && !@context.key?(var.name)
          raise MissingContextError.new("missing required context: #{var.name}")
        end
        if var.default && !@context.key?(var.name)
          @context[var.name] = Initializer.resolve(self, var.default)
        end
      end
    end

    class << self
      def resolve(instance, value)
        if value.respond_to?(:call)
          instance.instance_exec(&value)
        elsif value.is_a?(Symbol) && instance.respond_to?(value, true)
          instance.send(value)
        else
          value.deep_dup
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
coactive-0.6.0 lib/coactive/initializer.rb
coactive-0.5.2 lib/coactive/initializer.rb
coactive-0.5.1 lib/coactive/initializer.rb
coactive-0.5.0 lib/coactive/initializer.rb
coactive-0.4.1 lib/coactive/initializer.rb
coactive-0.4.0 lib/coactive/initializer.rb
coactive-0.3.0 lib/coactive/initializer.rb
coactive-0.2.2 lib/coactive/initializer.rb
coactive-0.2.1 lib/coactive/initializer.rb
coactive-0.2.0 lib/coactive/initializer.rb