Class: Reynard::Schema::ModelNaming

Inherits:
Object
  • Object
show all
Defined in:
lib/reynard/schema/model_naming.rb

Overview

Rummages through the specification to find a suitable model name for a response object.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(specification:, node:) ⇒ ModelNaming

Returns a new instance of ModelNaming.



7
8
9
10
# File 'lib/reynard/schema/model_naming.rb', line 7

def initialize(specification:, node:)
  @specification = specification
  @node = node
end

Class Method Details

.normalize_ref_model_name(model_name) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/reynard/schema/model_naming.rb', line 40

def self.normalize_ref_model_name(model_name)
  # 1. Unescape encoded characters to create an UTF-8 string
  # 2. Remove extensions for regularly used external schema files
  # 3. Replace all non-alphabetic characters with a space (not allowed in Ruby constant)
  # 4. Camelcase
  Rack::Utils.unescape_path(model_name)
             .gsub(/(.yml|.yaml|.json)\Z/, '')
             .gsub(/[^[:alpha:]]/, ' ')
             .gsub(/(\s+)([[:alpha:]])/) { Regexp.last_match(2).upcase }
             .gsub(/\A(.)/) { Regexp.last_match(1).upcase }
end

.ref_model_name(ref) ⇒ Object

Extracts a model name from a ref when there is a usable value.

ref_model_name("#/components/schemas/Library") => "Library"


34
35
36
37
38
# File 'lib/reynard/schema/model_naming.rb', line 34

def self.ref_model_name(ref)
  return unless ref

  normalize_ref_model_name(ref.split('/')&.last)
end

.singularize(name) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/reynard/schema/model_naming.rb', line 52

def self.singularize(name)
  case name
  when /ies$/
    "#{name[0..-4]}y"
  else
    name.chomp('s')
  end
end

.title_model_name(model_name) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/reynard/schema/model_naming.rb', line 21

def self.title_model_name(model_name)
  return unless model_name

  model_name
    .gsub(/[^[:alpha:]]/, ' ')
    .gsub(/\s{2,}/, ' ')
    .gsub(/(\s+)([[:alpha:]])/) { Regexp.last_match(2).upcase }
    .strip
end

Instance Method Details

#model_nameObject



12
13
14
15
16
17
18
19
# File 'lib/reynard/schema/model_naming.rb', line 12

def model_name
  model_name = determine_model_name
  if class_type == :array
    "#{model_name}Collection"
  else
    model_name
  end
end