Class: Etna::Injection

Inherits:
Object
  • Object
show all
Defined in:
lib/etna/injection.rb

Defined Under Namespace

Modules: FromHash

Class Method Summary collapse

Class Method Details

.inject_new(cls, hash, hash_has_string_keys, rest: nil, key_rest: nil, &missing_req_param_cb) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/etna/injection.rb', line 12

def self.inject_new(cls, hash, hash_has_string_keys, rest: nil, key_rest: nil, &missing_req_param_cb)
  args, kwds = prep_args(
    cls.instance_method(:initialize), hash, hash_has_string_keys,
    rest: rest, key_rest: key_rest, &missing_req_param_cb
  )

  cls.new(*args, **kwds)
end

.prep_args(method, hash, hash_has_string_keys, rest: nil, key_rest: nil, &missing_req_param_cb) ⇒ Object



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
49
50
51
52
53
54
55
# File 'lib/etna/injection.rb', line 21

def self.prep_args(method, hash, hash_has_string_keys, rest: nil, key_rest: nil, &missing_req_param_cb)
  new_k_params = {}
  new_p_params = []

  method.parameters.each do |type, p_key|
    h_key = hash_has_string_keys ? p_key.to_s : p_key
    if type == :rest && rest
      new_p_params.append(*rest)
    elsif type == :keyrest && key_rest
      new_k_params.update(key_rest)
    elsif type == :req || type == :opt
      if hash.include?(h_key)
        new_p_params << hash[h_key]
      elsif type == :req
        if block_given?
          new_p_params << missing_req_param_cb.call(h_key)
        else
          new_p_params << nil
        end
      end
    elsif type == :keyreq || type == :key
      if hash.include?(h_key)
        new_k_params[p_key] = hash[h_key]
      elsif type == :keyreq
        if block_given?
          new_k_params[p_key] = missing_req_param_cb.call(h_key)
        else
          new_k_params[p_key] = nil
        end
      end
    end
  end

  [new_p_params, new_k_params]
end