Class: Rage::OpenAPI::Parsers::Ext::ActiveRecord

Inherits:
Object
  • Object
show all
Defined in:
lib/rage/openapi/parsers/ext/active_record.rb

Constant Summary collapse

BLACKLISTED_ATTRIBUTES =
%w(id created_at updated_at)

Instance Method Summary collapse

Constructor Details

#initialize(namespace: Object) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.



6
7
8
# File 'lib/rage/openapi/parsers/ext/active_record.rb', line 6

def initialize(namespace: Object, **)
  @namespace = namespace
end

Instance Method Details

#known_definition?(str) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
14
15
# File 'lib/rage/openapi/parsers/ext/active_record.rb', line 10

def known_definition?(str)
  _, str = Rage::OpenAPI.__try_parse_collection(str)
  defined?(ActiveRecord::Base) && @namespace.const_get(str).ancestors.include?(ActiveRecord::Base)
rescue NameError
  false
end

#parse(klass_str) ⇒ Object



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
# File 'lib/rage/openapi/parsers/ext/active_record.rb', line 17

def parse(klass_str)
  is_collection, klass_str = Rage::OpenAPI.__try_parse_collection(klass_str)
  klass = @namespace.const_get(klass_str)

  schema = {}

  klass.attribute_types.each do |attr_name, attr_type|
    next if BLACKLISTED_ATTRIBUTES.include?(attr_name) ||
            attr_name.end_with?("_id") ||
            attr_name == klass.inheritance_column ||
            klass.defined_enums.include?(attr_name)

    schema[attr_name] = case attr_type.type
    when :integer
      { "type" => "integer" }
    when :boolean
      { "type" => "boolean" }
    when :binary
      { "type" => "string", "format" => "binary" }
    when :date
      { "type" => "string", "format" => "date" }
    when :datetime, :time
      { "type" => "string", "format" => "date-time" }
    when :float
      { "type" => "number", "format" => "float" }
    when :decimal
      { "type" => "number" }
    when :json
      { "type" => "object" }
    else
      { "type" => "string" }
    end
  end

  klass.defined_enums.each do |attr_name, mapping|
    schema[attr_name] = { "type" => "string", "enum" => mapping.keys }
  end

  result = { "type" => "object" }
  result["properties"] = schema if schema.any?

  result = { "type" => "array", "items" => result } if is_collection

  result
end