Module: Constructor

Defined in:
lib/constructor/constructor.rb,
lib/constructor/version.rb

Overview

:nodoc:#

Defined Under Namespace

Classes: ArgumentError

Constant Summary collapse

VERSION =
"2.0.0"

Instance Method Summary collapse

Instance Method Details

#initialize(args = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
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
# File 'lib/constructor/constructor.rb', line 2

def initialize(args = nil)
  config = self.class._constructor_config
  super(*config[:super_args]) if config[:super_args] && defined?(super)
  
  keys = self.class.constructor_keys
  if config[:require_args]
    # First, make sure we've got args of some kind
    unless args and args.keys and args.keys.size > 0 
      raise ArgumentError.new(keys)
    end
    # Scan for missing keys in the argument hash
    a_keys = args.keys
    missing = []
    keys.each do |ck|
      unless a_keys.member?(ck)
        missing << ck
      end
      a_keys.delete(ck) # Delete inbound keys as we address them
    end
    if missing.size > 0 || a_keys.size > 0
      raise ArgumentError.new(missing,a_keys)
    end
  end
  
  if args
    keys.each do |key|
      instance_variable_set "@#{key}", args[key]
    end
  end
  
  setup if respond_to?(:setup)
  
  if config[:constructor_block]
    instance_eval(&config[:constructor_block])
  end
end