-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathresponse.rb
63 lines (51 loc) · 1.57 KB
/
response.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
# frozen_string_literal: true
module MatrixSdk
# An usability wrapper for API responses as an extended [Hash]
# All results can be read as both hash keys and as read-only methods on the key
#
# @example Simple usage of the response wrapper to get the avatar URL
# resp = api.get_avatar_url(http://github.com/api.whoami?.user_id)
# # => { avatar_url: 'mxc://matrix.org/SDGdghriugerRg' }
# resp.is_a? Hash
# # => true
# resp.key? :avatar_url
# # => true
# resp.avatar_url
# # => 'mxc://matrix.org/SDGdghriugerRg'
# resp.api.set_avatar_url(http://github.com/...)
# # => {}
#
# @since 0.0.3
# @see Hash
# @!attribute [r] api
# @return [Api] The API connection that returned the response
module Response
def self.new(api, data)
if data.is_a? Array
raise ArgumentError, 'Input data was not an array of hashes' unless data.all? { |v| v.is_a? Hash }
data.each do |value|
Response.new api, value
end
return data
end
return data if data.instance_variables.include? :@api
raise ArgumentError, 'Input data was not a hash' unless data.is_a? Hash
data.extend(Extensions)
data.instance_variable_set(:@api, api)
data.select { |_k, v| v.is_a? Hash }
.each { |_v, v| Response.new api, v }
data
end
module Extensions
attr_reader :api
def respond_to_missing?(name, *_args)
return true if key? name
super
end
def method_missing(name, *args)
return fetch(name) if key?(name) && args.empty?
super
end
end
end
end