Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/shikashi/pick_argument.rb

Instance Method Summary collapse

Instance Method Details

#pick(*args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/shikashi/pick_argument.rb', line 39

def pick(*args)

  klass = args.pick_by_class Class
  hash_key = args.pick_by_class Symbol

  ary = []

  if klass
    ary = self.select{|x| x.instance_of? klass}

    if ary.size > 1
      raise ArgumentError, "ambiguous parameters of class #{klass}"
    end
  else
    ary = []
  end

  if hash_key
    each do |x|
      if x.instance_of? Hash
        if x[hash_key]
          ary << x[hash_key]
        end
      end
    end

    if ary.size > 1
      raise ArgumentError, "ambiguous parameters of class #{klass} and key '#{hash_key}'"
    end

  end

  if ary.size == 1
    return ary.first
  end

  unless block_given?
    raise ArgumentError, "missing mandatory argument '#{hash_key}' or of class #{klass}"
  end

  yield
end

#pick_by_class(klass) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/shikashi/pick_argument.rb', line 27

def pick_by_class(klass)
  klassary = self.select{|x| x.instance_of? klass}
  if klassary.size > 1
    raise ArgumentError, "ambiguous parameters of class #{klass}"
  elsif klassary.size == 1
    klassary.first
  else
    nil
  end

end