-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathentity.rb
More file actions
367 lines (287 loc) · 9.69 KB
/
entity.rb
File metadata and controls
367 lines (287 loc) · 9.69 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# frozen_string_literal: true
module NetboxClientRuby
module Entity # rubocop:disable Metrics/ModuleLength
include NetboxClientRuby::Communication
def self.included(other_klass)
other_klass.extend ClassMethods
end
module ClassMethods
##
# Expects ids in the following format:
# id 'an_id_field'
# id :an_id_field
# id 'an_id_field', 'another_id_field'
# id :an_id_field, :another_id_field
# id an_id_field: 'id_field_in_data'
# id an_id_field: :id_field_in_data
# id 'an_id_field' => :id_field_in_data
# id 'an_id_field' => 'id_field_in_data'
# id an_id_field: 'id_field_in_data', :another_id_field: 'id_field2_in_data'
#
def id(*fields)
return @id_fields if @id_fields
raise ArgumentError, "No 'id' was defined, but one is expected." if fields.empty?
@id_fields = load_attributes(fields)
@id_fields
end
def readonly_fields(*fields)
return @readonly_fields if @readonly_fields
@readonly_fields = fields.map(&:to_s)
end
def deletable(deletable = false) # rubocop:disable Style/OptionalBooleanParameter
@deletable ||= deletable
end
def path(path = nil)
@path ||= path
return @path if @path
raise ArgumentError, "No argument to 'path' was given."
end
def creation_path(creation_path = nil)
@creation_path ||= creation_path
return @creation_path if @creation_path
raise ArgumentError, "No argument to 'creation_path' was given."
end
# allowed values:
# <code>
# object_fields :field_a, :field_b, :field_c, 'fieldname_as_string'
# # next is ame as previous
# object_fields field_a: nil, field_b: nil, field_c: nil, 'fieldname_as_string': nil
# # next defines the types of the objects
# object_fields field_a: Klass, field_b: proc { |data| Klass.new data }, field_c: nil, 'fieldname_as_string'
# </code>
def object_fields(*fields_to_class_map)
return @object_fields if @object_fields
if fields_to_class_map.nil? || fields_to_class_map.empty?
@object_fields = {}
else
fields_map = sanitize_mapping(fields_to_class_map)
@object_fields = fields_map
end
end
private
def sanitize_mapping(fields_to_class_map) # rubocop:disable Metrics/MethodLength
fields_map = {}
fields_to_class_map.each do |field_definition|
if field_definition.is_a?(Hash)
fields_to_class_map[0].each do |field, klass_or_proc|
fields_map[field.to_s] = klass_or_proc
end
else
fields_map[field_definition.to_s] = nil
end
end
fields_map
end
def load_attributes(fields) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
id_fields = {}
if fields.first.is_a?(Hash)
fields.first.each { |key, value| id_fields[key.to_s] = value.to_s }
else
fields.map(&:to_s).each do |field|
field_as_string = field.to_s
id_fields[field_as_string] = field_as_string
end
end
id_fields.each_key do |field|
define_method(field) { instance_variable_get :"@#{field}" }
end
id_fields
end
end
def initialize(given_values = nil) # rubocop:disable Metrics/MethodLength
return self if given_values.nil?
if id_fields.count == 1 && !given_values.is_a?(Hash)
instance_variable_set(:"@#{id_fields.keys.first}", given_values)
return self
end
given_values.each do |field, value|
if id_fields.key? field.to_s
instance_variable_set :"@#{field}", value
else
# via method_missing, because it checks for readonly fields, etc.
method_missing("#{field}=", value)
end
end
self
end
def revert
dirty_data.clear
self
end
def reload
raise NetboxClientRuby::Error::LocalError, "Can't 'reload', this object has never been saved" unless ids_set?
@data = get
revert
self
end
def save
return post unless ids_set?
patch
end
def create(raw_data)
raise NetboxClientRuby::Error::LocalError, "Can't 'create', this object already exists" if ids_set?
@dirty_data = raw_data
post
end
def delete
raise NetboxClientRuby::Error::LocalError, "Can't delete unless deletable=true" unless deletable
return self if @deleted
@data = response connection.delete path
@deleted = true
revert
self
end
def update(new_values) # rubocop:disable Metrics/MethodLength
new_values.each do |attribute, values|
s_attribute = attribute.to_s
next if readonly_fields.include? s_attribute
sym_attr_writer = :"#{attribute}="
if methods.include?(sym_attr_writer)
public_send(sym_attr_writer, values)
else
dirty_data[s_attribute] = values
end
end
patch
end
def url
"#{connection.url_prefix}#{path}"
end
def raw_data!
data
end
def [](name)
s_name = name.to_s
dirty_data[s_name] || data[s_name]
end
def []=(name, value)
dirty_data[name.to_s] = value
end
def method_missing(name_as_symbol, *args, &block) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength
name = name_as_symbol.to_s
if name.end_with?('=')
is_readonly_field = readonly_fields.include?(name[0..-2])
is_instance_variable = instance_variables.include?(:"@#{name[0..-2]}")
not_this_classes_business = is_readonly_field || is_instance_variable
return super if not_this_classes_business
dirty_data[name[0..-2]] = args[0]
return args[0]
end
return dirty_data[name] if dirty_data.key? name
return objectify(data[name], object_fields[name]) if object_fields.key? name
return data[name] if data.is_a?(Hash) && data.key?(name)
super
end
def respond_to_missing?(name_as_symbol, *args) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
name = name_as_symbol.to_s
return false if name.end_with?('=') && readonly_fields.include?(name[0..-2])
return false if name.end_with?('=') && instance_variables.include?(name[0..-2])
return true if dirty_data.key? name
return true if object_fields.key? name
return true if data.is_a?(Hash) && data.key?(name)
super
end
##
# :internal: Used to pre-populate an entity
def data=(data)
@data = data
end
alias get! reload
alias remove delete
private
def post
return self if dirty_data.empty?
@data = response connection.post creation_path, dirty_data
extract_ids
revert
self
end
def patch
return self if dirty_data.empty?
@data ||= {}
response_data = response connection.patch(path, dirty_data)
@data.merge! response_data
revert
self
end
def data
@data ||= get
end
def get
response connection.get path unless @deleted or !ids_set?
end
def readonly_fields
self.class.readonly_fields
end
def deletable
self.class.deletable
end
def object_fields
self.class.object_fields
end
def hash_to_object(hash)
objectified_class = Class.new
objectified_instance = objectified_class.new
hash.each do |k, v|
variable_name = sanitize_variable_name(k)
variable_name = "_#{variable_name}" if objectified_instance.methods.map(&:to_s).include?(variable_name)
objectified_instance.instance_variable_set(:"@#{variable_name}", v)
objectified_class.send(:define_method, variable_name, proc { instance_variable_get(:"@#{variable_name}") })
end
objectified_instance
end
def sanitize_variable_name(raw_name)
raw_name.gsub(/[^a-zA-Z0-9_]/, '_')
end
def data_to_obj(raw_data, klass_or_proc = nil)
if klass_or_proc.nil?
hash_to_object raw_data
elsif klass_or_proc.is_a? Proc
klass_or_proc.call raw_data
else
klass_or_proc.new raw_data
end
end
def objectify(raw_data, klass_or_proc = nil)
return nil if raw_data.nil?
return data_to_obj(raw_data, klass_or_proc) unless raw_data.is_a? Array
raw_data.map do |raw_data_entry|
data_to_obj(raw_data_entry, klass_or_proc)
end
end
def creation_path
@creation_path ||= replace_path_variables_in self.class.creation_path
end
def path
@path ||= replace_path_variables_in self.class.path
end
def replace_path_variables_in(path)
interpreted_path = path.dup
path.scan(/:([a-zA-Z_][a-zA-Z0-9_]+[!?=]?)/) do |match, *|
path_variable_value = send(match)
return interpreted_path.gsub! ":#{match}", path_variable_value.to_s unless path_variable_value.nil?
raise NetboxClientRuby::Error::LocalError,
"Received 'nil' while replacing ':#{match}' in '#{path}' with a value."
end
interpreted_path
end
def dirty_data
@dirty_data ||= {}
end
def id_fields
self.class.id
end
def extract_ids
id_fields.each do |id_attr, id_field|
unless data.key?(id_field)
raise NetboxClientRuby::Error::LocalError,
"Can't find the id field '#{id_field}' in the received data."
end
instance_variable_set(:"@#{id_attr}", data[id_field])
end
end
def ids_set?
id_fields.map { |id_attr, _| instance_variable_get(:"@#{id_attr}") }.all?
end
end
end