Class: JunglePath::Query::NestedHashSorter

Inherits:
Object
  • Object
show all
Defined in:
lib/jungle_path/query/nested_hash_sorter.rb

Instance Method Summary collapse

Constructor Details

#initialize(paths, sort_orders) ⇒ NestedHashSorter

Returns a new instance of NestedHashSorter.



4
5
6
7
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 4

def initialize(paths, sort_orders)
	@paths = paths
	@sort_orders = sort_orders
end

Instance Method Details

#get_array_left(a, b) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 48

def get_array_left(a, b)
	values = []
	@paths.each_index do |i|
		keys = @paths[i]
		sort_order = @sort_orders[i]
		if sort_order == :asc
			values << get_value(a, keys)
		else
			values << get_value(b, keys)
		end
	end
	#puts "left values: #{values}."
	values
end

#get_array_right(a, b) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 63

def get_array_right(a, b)
	values = []
	@paths.each_index do |i|
		keys = @paths[i]
		sort_order = @sort_orders[i]
		if sort_order == :asc
			values << get_value(b, keys)
		else
			values << get_value(a, keys)
		end
	end
	#puts "right values: #{values}."
	values
end

#get_value(hash, keys) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 78

def get_value(hash, keys)
	#extract a value from a nested hash
	#puts "get_value:\n  hash: #{hash}\n  keys: #{keys}."
	#puts ""
	h = hash
	keys.each do |key|
		if h.class == Array
			h = h[0][key]
		else
			h = h[key]
		end
	end
	h
end

#sort(a, b) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 9

def sort(a, b)
	#value = get_array_left(a, b) <=> get_array_right(a, b)
	#can't do the above if some of the array values can be nil. Instead look at each array item individually and handle any nils:
	#puts 'in sort'
	value = sort_handle_nils(get_array_left(a, b), get_array_right(a, b))
	value
end

#sort_handle_nils(array_a, array_b) ⇒ Object



17
18
19
20
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
# File 'lib/jungle_path/query/nested_hash_sorter.rb', line 17

def sort_handle_nils(array_a, array_b)
	#puts 'in sort_handle_nils'
	#puts "array_a: #{array_a}."
	#puts "array_b: #{array_b}."
	i = 0
	value = 0
	while i < array_a.length and value == 0
		v = 0
		a = array_a[i]
		b = array_b[i]
		#puts "a: #{a}."
		#puts "b: #{b}."
		a = 1 if a.class == TrueClass
		a = 0 if a.class == FalseClass
		b = 1 if b.class == TrueClass
		b = 0 if b.class == FalseClass
		if a == nil and b == nil
			v = 0
		elsif a == nil
			v = -1
		elsif b == nil
			v = 1
		else
			v = a <=> b
		end
		value = v
		i = i + 1
	end
	value
end