Class: Scorpio::ResourceBase

Inherits:
Object
  • Object
show all
Includes:
FingerprintHash
Defined in:
lib/scorpio/resource_base.rb,
lib/scorpio/pickle_adapter.rb

Defined Under Namespace

Modules: PickleAdapter

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from FingerprintHash

#==, #hash

Constructor Details

#initialize(attributes = {}, options = {}) ⇒ ResourceBase

Returns a new instance of ResourceBase.



489
490
491
492
493
# File 'lib/scorpio/resource_base.rb', line 489

def initialize(attributes = {}, options = {})
  @attributes = Scorpio.stringify_symbol_keys(attributes)
  @options = Scorpio.stringify_symbol_keys(options)
  @persisted = !!@options['persisted']
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



495
496
497
# File 'lib/scorpio/resource_base.rb', line 495

def attributes
  @attributes
end

#optionsObject (readonly)

Returns the value of attribute options.



496
497
498
# File 'lib/scorpio/resource_base.rb', line 496

def options
  @options
end

Class Method Details

.all_schema_propertiesObject



146
147
148
# File 'lib/scorpio/resource_base.rb', line 146

def all_schema_properties
  represented_schemas.map(&:described_hash_property_names).inject(Set.new, &:|)
end

.call_operation(operation, call_params: nil, model_attributes: nil) ⇒ Object



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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/scorpio/resource_base.rb', line 252

def call_operation(operation, call_params: nil, model_attributes: nil)
  call_params = Scorpio.stringify_symbol_keys(call_params) if call_params.is_a?(Hash)
  model_attributes = Scorpio.stringify_symbol_keys(model_attributes || {})
  http_method = operation.http_method.downcase.to_sym
  path_template = Addressable::Template.new(operation.path)
  template_params = model_attributes
  template_params = template_params.merge(call_params) if call_params.is_a?(Hash)
  missing_variables = path_template.variables - template_params.keys
  if missing_variables.any?
    raise(ArgumentError, "path #{operation.path} for operation #{operation.operationId} requires attributes " +
      "which were missing: #{missing_variables.inspect}")
  end
  empty_variables = path_template.variables.select { |v| template_params[v].to_s.empty? }
  if empty_variables.any?
    raise(ArgumentError, "path #{operation.path} for operation #{operation.operationId} requires attributes " +
      "which were empty: #{empty_variables.inspect}")
  end
  path = path_template.expand(template_params)
  # we do not use Addressable::URI#join as the paths should just be concatenated, not resolved.
  # we use File.join just to deal with consecutive slashes.
  url = File.join(base_url, path)
  url = Addressable::URI.parse(url)
  # assume that call_params must be included somewhere. model_attributes are a source of required things
  # but not required to be here.
  other_params = call_params
  if other_params.is_a?(Hash)
    other_params.reject! { |k, _| path_template.variables.include?(k) }
  end

  if operation.request_schema
    # TODO deal with model_attributes / call_params better in nested whatever
    if call_params.nil?
      body = request_body_for_schema(model_attributes, operation.request_schema)
    elsif call_params.is_a?(Hash)
      body = request_body_for_schema(model_attributes.merge(call_params), operation.request_schema)
      body = body.merge(call_params) # TODO
    else
      body = call_params
    end
  else
    if other_params
      if METHODS_WITH_BODIES.any? { |m| m.to_s == http_method.downcase.to_s }
        body = other_params
      else
        if other_params.is_a?(Hash)
          # TODO pay more attention to 'parameters' api method attribute
          url.query_values = other_params
        else
          raise
        end
      end
    end
  end

  request_headers = {}

  if METHODS_WITH_BODIES.any? { |m| m.to_s == http_method.downcase.to_s } && body != nil
    consumes = operation.consumes || openapi_document.consumes || []
    if consumes.include?("application/json") || (!body.respond_to?(:to_str) && consumes.empty?)
    # if we have a body that's not a string and no indication of how to serialize it, we guess json.
      request_headers['Content-Type'] = "application/json"
      unless body.respond_to?(:to_str)
        body = ::JSON.pretty_generate(Typelike.as_json(body))
      end
    elsif consumes.include?("application/x-www-form-urlencoded")
      request_headers['Content-Type'] = "application/x-www-form-urlencoded"
      unless body.respond_to?(:to_str)
        body = URI.encode_www_form(body)
      end
    elsif body.is_a?(String)
      if consumes.size == 1
        request_headers['Content-Type'] = consumes.first
      end
    else
      raise("do not know how to serialize for #{consumes.inspect}: #{body.pretty_inspect.chomp}")
    end
  end

  response = connection.run_request(http_method, url, body, request_headers)

  if response.media_type == 'application/json'
    if response.body.empty?
      response_object = nil
    else
      begin
        response_object = ::JSON.parse(response.body)
      rescue ::JSON::ParserError
        # TODO warn
        response_object = response.body
      end
    end
  else
    response_object = response.body
  end

  if operation.responses
    _, operation_response = operation.responses.detect { |k, v| k.to_s == response.status.to_s }
    operation_response ||= operation.responses['default']
    response_schema = operation_response['schema'] if operation_response
  end
  if response_schema
    # not too sure about this, but I don't think it makes sense to instantiate things that are
    # not hash or array as a SchemaInstanceBase
    if response_object.respond_to?(:to_hash) || response_object.respond_to?(:to_ary)
      response_object = Scorpio.class_for_schema(response_schema).new(response_object)
    end
  end

  error_class = Scorpio.error_classes_by_status[response.status]
  error_class ||= if (400..499).include?(response.status)
    ClientError
  elsif (500..599).include?(response.status)
    ServerError
  elsif !response.success?
    HTTPError
  end
  if error_class
    message = "Error calling operation #{operation.operationId} on #{self}:\n" + (response.env[:raw_body] || response.env.body)
    raise(error_class.new(message).tap do |e|
      e.faraday_response = response
      e.response_object = response_object
    end)
  end

  initialize_options = {
    'persisted' => true,
    'source' => {'operationId' => operation.operationId, 'call_params' => call_params, 'url' => url.to_s},
    'response' => response,
  }
  response_object_to_instances(response_object, initialize_options)
end

.connectionObject



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/scorpio/resource_base.rb', line 240

def connection
  Faraday.new(:headers => {'User-Agent' => user_agent}) do |c|
    faraday_request_middleware.each do |m|
      c.request(*m)
    end
    faraday_response_middleware.each do |m|
      c.response(*m)
    end
    c.adapter(*faraday_adapter)
  end
end

.define_inheritable_accessor(accessor, options = {}) ⇒ Object



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
# File 'lib/scorpio/resource_base.rb', line 13

def define_inheritable_accessor(accessor, options = {})
  if options[:default_getter]
    # the value before the field is set (overwritten) is the result of the default_getter proc
    define_singleton_method(accessor, &options[:default_getter])
  else
    # the value before the field is set (overwritten) is the default_value (which is nil if not specified)
    default_value = options[:default_value]
    define_singleton_method(accessor) { default_value }
  end
  # field setter method. redefines the getter, replacing the method with one that returns the
  # setter's argument (that being inherited to the scope of the define_method(accessor) block
  define_singleton_method(:"#{accessor}=") do |value|
    # the setter operates on the singleton class of the receiver (self)
    singleton_class.instance_exec(value, self) do |value_, klass|
      # remove a previous getter. NameError is raised if a getter is not defined on this class;
      # this may be ignored.
      begin
        remove_method(accessor)
      rescue NameError
      end
      # getter method
      define_method(accessor) { value_ }
      # invoke on_set callback defined on the class
      if options[:on_set]
        klass.instance_exec(&options[:on_set])
      end
    end
  end
end

.method_names_by_operationObject



202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/scorpio/resource_base.rb', line 202

def method_names_by_operation
  @method_names_by_operation ||= Hash.new do |h, operation|
    h[operation] = begin
      raise(ArgumentError, operation.pretty_inspect) unless operation.is_a?(Scorpio::OpenAPI::V2::Operation)

      if operation.tags.respond_to?(:to_ary) && operation.tags.include?(tag_name) && operation.operationId =~ /\A#{Regexp.escape(tag_name)}\.(\w+)\z/
        method_name = $1
      else
        method_name = operation.operationId
      end
    end
  end
end

.openapi_documentObject



100
101
102
# File 'lib/scorpio/resource_base.rb', line 100

def openapi_document
  nil
end

.openapi_document=(openapi_document) ⇒ Object



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
# File 'lib/scorpio/resource_base.rb', line 104

def openapi_document=(openapi_document)
  self.openapi_document_class = self

  if openapi_document.is_a?(Hash)
    openapi_document = OpenAPI::V2::Document.new(openapi_document)
  end

  begin
    singleton_class.instance_exec { remove_method(:openapi_document) }
  rescue NameError
  end
  define_singleton_method(:openapi_document) { openapi_document }
  define_singleton_method(:openapi_document=) do
    if self == openapi_document_class
      raise(ArgumentError, "openapi_document may only be set once on #{self.inspect}")
    else
      raise(ArgumentError, "openapi_document may not be overridden on subclass #{self.inspect} after it was set on #{openapi_document_class.inspect}")
    end
  end
  update_dynamic_methods

  openapi_document.paths.each do |path, path_item|
    path_item.each do |http_method, operation|
      next if http_method == 'parameters' # parameters is not an operation. TOOD maybe just select the keys that are http methods?
      unless operation.is_a?(Scorpio::OpenAPI::V2::Operation)
        raise("bad operation at #{operation.fragment}: #{operation.pretty_inspect}")
      end
      operation.path = path
      operation.http_method = http_method
    end
  end

  openapi_document.validate!

  update_dynamic_methods
end

.operation_for_resource_class?(operation) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
168
169
170
171
172
173
174
175
# File 'lib/scorpio/resource_base.rb', line 165

def operation_for_resource_class?(operation)
  return false unless tag_name

  return true if operation.tags.respond_to?(:to_ary) && operation.tags.include?(tag_name)

  if operation.request_schema && represented_schemas.include?(operation.request_schema)
    return true
  end

  return false
end

.operation_for_resource_instance?(operation) ⇒ Boolean

Returns:

  • (Boolean)


177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/scorpio/resource_base.rb', line 177

def operation_for_resource_instance?(operation)
  return false unless operation_for_resource_class?(operation)

  # define an instance method if the request schema is for this model 
  request_resource_is_self = operation.request_schema && represented_schemas.include?(operation.request_schema)

  # also define an instance method depending on certain attributes the request description 
  # might have in common with the model's schema attributes
  request_attributes = []
  # if the path has attributes in common with model schema attributes, we'll define on 
  # instance method
  request_attributes |= Addressable::Template.new(operation.path).variables
  # TODO if the method request schema has attributes in common with the model schema attributes,
  # should we define an instance method?
  #request_attributes |= request_schema && request_schema['type'] == 'object' && request_schema['properties'] ?
  #  request_schema['properties'].keys : []
  # TODO if the method parameters have attributes in common with the model schema attributes,
  # should we define an instance method?
  #request_attributes |= method_desc['parameters'] ? method_desc['parameters'].keys : []

  schema_attributes = represented_schemas.map(&:described_hash_property_names).inject(Set.new, &:|)

  return request_resource_is_self || (request_attributes & schema_attributes.to_a).any?
end

.request_body_for_schema(object, schema) ⇒ Object



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/scorpio/resource_base.rb', line 384

def request_body_for_schema(object, schema)
  if object.is_a?(Scorpio::ResourceBase)
    # TODO request_schema_fail unless schema is for given model type 
    request_body_for_schema(object.attributes, schema)
  elsif object.is_a?(Scorpio::SchemaInstanceBase)
    request_body_for_schema(object.instance, schema)
  elsif object.is_a?(Scorpio::JSON::Node)
    request_body_for_schema(object.content, schema)
  else
    if object.is_a?(Hash)
      object.map do |key, value|
        if schema
          if schema['type'] == 'object'
            # TODO code dup with response_object_to_instances
            if schema['properties'] && schema['properties'][key]
              subschema = schema['properties'][key]
              include_pair = true
            else
              if schema['patternProperties']
                _, pattern_schema = schema['patternProperties'].detect do |pattern, _|
                  key =~ Regexp.new(pattern) # TODO map pattern to ruby syntax
                end
              end
              if pattern_schema
                subschema = pattern_schema
                include_pair = true
              else
                if schema['additionalProperties'] == false
                  include_pair = false
                elsif schema['additionalProperties'] == nil
                  # TODO decide on this (can combine with `else` if treating nil same as schema present)
                  include_pair = true
                  subschema = nil
                else
                  include_pair = true
                  subschema = schema['additionalProperties']
                end
              end
            end
          elsif schema['type']
            request_schema_fail(object, schema)
          else
            # TODO not sure
            include_pair = true
            subschema = nil
          end
        end
        if include_pair
          {key => request_body_for_schema(value, subschema)}
        else
          {}
        end
      end.inject({}, &:update)
    elsif object.is_a?(Array) || object.is_a?(Set)
      object.map do |el|
        if schema
          if schema['type'] == 'array'
            # TODO index based subschema or whatever else works for array
            subschema = schema['items']
          else
            request_schema_fail(object, schema)
          end
        end
        request_body_for_schema(el, subschema)
      end
    else
      # TODO maybe raise on anything not serializable 
      # TODO check conformance to schema, request_schema_fail if not
      object
    end
  end
end

.request_schema_fail(object, schema) ⇒ Object



457
458
459
# File 'lib/scorpio/resource_base.rb', line 457

def request_schema_fail(object, schema)
  raise(RequestSchemaFailure, "object does not conform to schema.\nobject = #{object.pretty_inspect}\nschema = #{::JSON.pretty_generate(schema, quirks_mode: true)}")
end

.response_object_to_instances(object, initialize_options = {}) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/scorpio/resource_base.rb', line 461

def response_object_to_instances(object, initialize_options = {})
  if object.is_a?(SchemaInstanceBase)
    model = models_by_schema[object.schema]
  end

  if object.respond_to?(:to_hash)
    out = Typelike.modified_copy(object) do
      object.map do |key, value|
        {key => response_object_to_instances(value, initialize_options)}
      end.inject({}, &:update)
    end
    if model
      model.new(out, initialize_options)
    else
      out
    end
  elsif object.respond_to?(:to_ary)
    Typelike.modified_copy(object) do
      object.map do |element|
        response_object_to_instances(element, initialize_options)
      end
    end
  else
    object
  end
end

.update_class_and_instance_api_methodsObject



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/scorpio/resource_base.rb', line 216

def update_class_and_instance_api_methods
  openapi_document.paths.each do |path, path_item|
    path_item.each do |http_method, operation|
      next if http_method == 'parameters' # parameters is not an operation. TOOD maybe just select the keys that are http methods?
      operation.path = path
      operation.http_method = http_method
      method_name = method_names_by_operation[operation]
      # class method
      if operation_for_resource_class?(operation) && !respond_to?(method_name)
        define_singleton_method(method_name) do |call_params = nil|
          call_operation(operation, call_params: call_params)
        end
      end

      # instance method
      if operation_for_resource_instance?(operation) && !method_defined?(method_name)
        define_method(method_name) do |call_params = nil|
          call_operation(operation, call_params: call_params)
        end
      end
    end
  end
end

.update_dynamic_methodsObject



141
142
143
144
# File 'lib/scorpio/resource_base.rb', line 141

def update_dynamic_methods
  update_class_and_instance_api_methods
  update_instance_accessors
end

.update_instance_accessorsObject



150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/scorpio/resource_base.rb', line 150

def update_instance_accessors
  all_schema_properties.each do |property_name|
    unless method_defined?(property_name)
      define_method(property_name) do
        self[property_name]
      end
    end
    unless method_defined?(:"#{property_name}=")
      define_method(:"#{property_name}=") do |value|
        self[property_name] = value
      end
    end
  end
end

Instance Method Details

#[](key) ⇒ Object



502
503
504
# File 'lib/scorpio/resource_base.rb', line 502

def [](key)
  @attributes[key]
end

#[]=(key, value) ⇒ Object



506
507
508
# File 'lib/scorpio/resource_base.rb', line 506

def []=(key, value)
  @attributes[key] = value
end

#as_jsonObject



537
538
539
# File 'lib/scorpio/resource_base.rb', line 537

def as_json
  Typelike.as_json(@attributes)
end

#call_api_method(method_name, call_params: nil) ⇒ Object



510
511
512
513
# File 'lib/scorpio/resource_base.rb', line 510

def call_api_method(method_name, call_params: nil)
  operation = self.class.method_names_by_operation.invert[method_name] || raise(ArgumentError)
  call_operation(operation, call_params: call_params)
end

#call_operation(operation, call_params: nil) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/scorpio/resource_base.rb', line 515

def call_operation(operation, call_params: nil)
  response = self.class.call_operation(operation, call_params: call_params, model_attributes: self.attributes)

  # if we're making a POST or PUT and the request schema is this resource, we'll assume that
  # the request is persisting this resource
  request_resource_is_self = operation.request_schema && self.class.represented_schemas.include?(operation.request_schema)
  if @options['response'] && @options['response'].status && operation.responses
    _, response_schema_node = operation.responses.detect { |k, v| k.to_s == @options['response'].status.to_s }
  end
  response_schema = Scorpio::Schema.new(response_schema_node) if response_schema_node
  response_resource_is_self = response_schema && self.class.represented_schemas.include?(response_schema)
  if request_resource_is_self && %w(put post).include?(operation.http_method.to_s.downcase)
    @persisted = true

    if response_resource_is_self
      @attributes = response.attributes
    end
  end

  response
end

#fingerprintObject



558
559
560
# File 'lib/scorpio/resource_base.rb', line 558

def fingerprint
  {class: self.class, attributes: Typelike.as_json(@attributes)}
end

#inspectObject



541
542
543
# File 'lib/scorpio/resource_base.rb', line 541

def inspect
  "\#<#{self.class.inspect} #{attributes.inspect}>"
end

#persisted?Boolean

Returns:

  • (Boolean)


498
499
500
# File 'lib/scorpio/resource_base.rb', line 498

def persisted?
  @persisted
end

#pretty_print(q) ⇒ Object



544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/scorpio/resource_base.rb', line 544

def pretty_print(q)
  q.instance_exec(self) do |obj|
    text "\#<#{obj.class.inspect}"
    group_sub {
      nest(2) {
        breakable ' '
        pp obj.attributes
      }
    }
    breakable ''
    text '>'
  end
end