Class: Burp

Inherits:
Hash
  • Object
show all
Defined in:
lib/burp.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node_list, id_key, data_filter = nil) ⇒ Burp

Converts a list of data (i.e. an array) into a ruby hash structure

It takes as arguments,the array of hashes (each hash representing node data) and a field in the hash (node data) to use as the key for the returned hash



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/burp.rb', line 7

def initialize(node_list, id_key, data_filter = nil)
  @left_overs = []
  node_list.map do |raw_node|
    node_id = find_id(raw_node, id_key)
    if node_ok?(raw_node, node_id)
      node_burp(raw_node, node_id, data_filter)  #adds to self (i.e. this hash)
    else
      @left_overs << raw_node
    end
  end
end

Instance Attribute Details

#left_oversObject (readonly)

Returns the value of attribute left_overs.



2
3
4
# File 'lib/burp.rb', line 2

def left_overs
  @left_overs
end

Instance Method Details

#find_data(node, data_filter) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/burp.rb', line 40

def find_data(node, data_filter)
  return node unless data_filter
  if data_filter.is_a? Proc
    node_data = data_filter.call(node)
  else
    #Done this way to allow any object that supports [], []= and has_key? methods
    #I'm intentionally avoiding Hash#select/reject for this (selfish) reason
    data_filter = [data_filter].flatten
    new_data = {}
    data_filter.each do |key|
      if node.has_key?(key)
        new_data[key] = validate(node, key)
      end
    end
    new_data
  end
end

#find_id(node, id_key) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/burp.rb', line 32

def find_id(node, id_key)
  if id_key.is_a? Proc
    id_key.call(node)
  else
    validate(node, id_key)
  end
end

#node_burp(raw_node, node_id, data_filter) ⇒ Object



26
27
28
29
# File 'lib/burp.rb', line 26

def node_burp(raw_node, node_id, data_filter)
  node_data = find_data(raw_node, data_filter)
  self[node_id] = node_data
end

#node_ok?(raw_node, node_id) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
# File 'lib/burp.rb', line 19

def node_ok?(raw_node, node_id)
  resp = true
  resp = false if self.has_key?(node_id)
  resp = false if raw_node && node_id.nil?
  resp
end

#validate(node, id) ⇒ Object



58
59
60
61
62
63
64
65
# File 'lib/burp.rb', line 58

def validate(node, id)
  begin
    node[id]
  rescue TypeError  #replacing an unhelpful error with something more helpful
    raise ArgumentError, "Can't use #{id.inspect} as a valid key in #{node.inspect}. "\
      "Maybe you're trying a hash method on something other than a hash?"
  end
end