forked from ruby-grape/grape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_stack.rb
91 lines (80 loc) · 2.22 KB
/
hash_stack.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
81
82
83
84
85
86
87
88
89
90
91
module Grape
module Util
# HashStack is a stack of hashes. When retrieving a value, keys of the top
# hash on the stack take precendent over the lower keys.
class HashStack
# Unmerged array of hashes to represent the stack.
# The top of the stack is the last element.
attr_reader :stack
# TODO: handle aggregates
def initialize
@stack = [{}]
end
# Returns the top hash on the stack
def peek
@stack.last
end
# Add a new hash to the top of the stack.
#
# @param hash [Hash] optional hash to be pushed. Defaults to empty hash
# @return [HashStack]
def push(hash = {})
@stack.push(hash)
self
end
def pop
@stack.pop
end
# Looks through the stack for the first frame that matches :key
#
# @param key [Symbol] key to look for in hash frames
# @return value of given key after merging the stack
def get(key)
(@stack.length - 1).downto(0).each do |i|
return @stack[i][key] if @stack[i].key? key
end
nil
end
alias_method :[], :get
# Replace a value on the top hash of the stack.
#
# @param key [Symbol] The key to set.
# @param value [Object] The value to set.
def set(key, value)
peek[key.to_sym] = value
end
alias_method :[]=, :set
# Replace multiple values on the top hash of the stack.
#
# @param hash [Hash] Hash of values to be merged in.
def update(hash)
peek.merge!(hash)
self
end
# Adds addition value into the top hash of the stack
def imbue(key, value)
current = peek[key.to_sym]
if current.is_a?(Array)
current.concat(value)
elsif current.is_a?(Hash)
current.merge!(value)
else
set(key, value)
end
end
# Prepend another HashStack's to self
def prepend(hash_stack)
@stack.unshift *hash_stack.stack
self
end
# Concatenate another HashStack's to self
def concat(hash_stack)
@stack.concat hash_stack.stack
self
end
def to_s
@stack.to_s
end
end
end
end