Module: ArrayOfHashes

Includes:
Enumerable
Included in:
Player, Strategy, StrategyProfile
Defined in:
lib/minigame/array_of_hashes.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

creates a singleton method on the included class which avoids having to put ‘required_keys’ into the included classes initialize method



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/minigame/array_of_hashes.rb', line 23

def self.included(klass)
  class << klass
    attr_accessor :keys
    def required_keys(*keys)
      # force single keys to be an array
      keys = [keys].flatten
      keys.each do |x|
        raise 'Not a symbol' if !keys[0].is_a? Symbol
      end
      @keys=keys
    end
  end
end

Instance Method Details

#<<(val) ⇒ Object



63
64
65
66
# File 'lib/minigame/array_of_hashes.rb', line 63

def <<(val)
  check_keys(val)
  @array_of_hashes << val
end

#check_array(array_of_hashes) ⇒ Object



51
52
53
54
# File 'lib/minigame/array_of_hashes.rb', line 51

def check_array(array_of_hashes)
  raise 'Not an array' if !array_of_hashes.is_a? Array
  array_of_hashes.each{|x|check_keys(x)}
end

#check_keys(val) ⇒ Object



56
57
58
59
60
61
# File 'lib/minigame/array_of_hashes.rb', line 56

def check_keys(val)
  raise "Not a Hash" if val.class != Hash 
  @keys.each do |x|
    raise "#{x.to_s.capitalize} required" if !val.keys.include?(x)
  end
end

#each(&block) ⇒ Object



14
15
16
17
18
# File 'lib/minigame/array_of_hashes.rb', line 14

def each(&block)
  @array_of_hashes.each do |matchup|
    block.call(matchup)
  end
end

#initialize(*array_of_hashes) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/minigame/array_of_hashes.rb', line 4

def initialize(*array_of_hashes)
  array_of_hashes = [array_of_hashes].flatten
  @keys ||=[]
  # checks to see if required_keys was called 
  # as a singleton method on the included class
  @keys = self.class.keys if self.class.keys
  check_array(array_of_hashes)
  @array_of_hashes=array_of_hashes
end

#required_keys(*keys) ⇒ Object

required keys available on the instance



38
39
40
41
42
43
44
45
# File 'lib/minigame/array_of_hashes.rb', line 38

def required_keys(*keys)
  # force single keys to be an array
  keys = [keys].flatten
  keys.each do |x|
    raise 'Not a symbol' if !keys[0].is_a? Symbol
  end
  @keys = keys
end

#required_keys=(keys) ⇒ Object



47
48
49
# File 'lib/minigame/array_of_hashes.rb', line 47

def required_keys=(keys)
  required_keys(keys)
end