Module: BBLib::SimpleInit

Defined in:
lib/mixins/simple_init.rb

Overview

Allows any public setter method to be called during initialization using keyword arguments. Add include BBLib::SimpleInit or prepend BBLib::SimpleInit to classes to add this behavior.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

INIT_TYPES =
[:strict, :loose].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#_init_typeObject (readonly)

Returns the value of attribute _init_type.



7
8
9
# File 'lib/mixins/simple_init.rb', line 7

def _init_type
  @_init_type
end

Class Method Details

.included(base) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mixins/simple_init.rb', line 11

def self.included(base)
  base.extend ClassMethods
  base.class_eval do
    define_method(:initialize) do |*args, &block|
      send(:simple_setup) if respond_to?(:simple_setup, true)
      send(:simple_preinit, *args, &block) if respond_to?(:simple_preinit, true)
      _initialize(*args, &block)
      send(:simple_init, *args, &block) if respond_to?(:simple_init, true)
      if block && !_attrs.any? { |k, v| v[:options][:arg_at] == :block }
        result = instance_eval(&block)
        simple_init_block_result(result) if respond_to?(:simple_init_block_result, true)
      end
    end
  end

  if BBLib.in_opal?
    base.singleton_class.class_eval do
      alias __new new

      def new(*args, &block)
        named = BBLib.named_args(*args)
        if init_foundation && named[init_foundation_method] && ((named[init_foundation_method] != self.send(init_foundation_method)) rescue false)
          klass = [self, descendants].flatten.find do |k|
            if init_foundation_compare
              init_foundation_compare.call(k.send(init_foundation_method), named[init_foundation_method])
            else
              k.send(init_foundation_method).to_s == named[init_foundation_method].to_s
            end
          end
          raise ArgumentError, "Unknown #{init_foundation_method} \"#{named[init_foundation_method]}\" for #{self}" unless klass
          klass == self ? __new(*args, &block) : klass.new(*args, &block)
        else
          __new(*args, &block)
        end
      end
    end
  end
end