Class: GrapeSwagger::FastJsonapi::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/grape_fast_jsonapi/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, endpoint) ⇒ Parser

Returns a new instance of Parser.



9
10
11
12
# File 'lib/grape_fast_jsonapi/parser.rb', line 9

def initialize(model, endpoint)
  @model = model
  @endpoint = endpoint
end

Instance Attribute Details

#endpointObject (readonly)

Returns the value of attribute endpoint.



7
8
9
# File 'lib/grape_fast_jsonapi/parser.rb', line 7

def endpoint
  @endpoint
end

#modelObject (readonly)

Returns the value of attribute model.



6
7
8
# File 'lib/grape_fast_jsonapi/parser.rb', line 6

def model
  @model
end

Instance Method Details

#callObject



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
# File 'lib/grape_fast_jsonapi/parser.rb', line 14

def call
  schema = default_schema

  attributes_hash = if (defined? ActiveRecord)
                map_model_attributes.symbolize_keys.merge(map_active_record_columns_to_attributes.symbolize_keys)
              else
                map_model_attributes.symbolize_keys
              end

  attributes_hash.each do |attribute, type|
    schema[:data][:properties][:attributes][:properties][attribute] = { type: type }
    example_method = "#{type}_example"
    unless self.respond_to?(example_method, true)
      puts "WARN unexpected type encountered, missing #{example_method}  --use string example instead"
      example_method = "string_example"
    end
    schema[:data][:example][:attributes][attribute] = send example_method
  end

  relationships_hash = model.relationships_to_serialize || []

  # If relationship has :key set different than association name, it should be rendered under that key
  relationships_hash =
    relationships_hash.each_with_object({}) { |(_relationship_name, relationship), accu| accu[relationship.key] = relationship }

  relationships_hash.each do |model_type, relationship_data|
    relationships_attributes = relationship_data.instance_values.symbolize_keys
    schema[:data][:properties][:relationships][:properties][model_type] = {
      type: :object,
      properties: relationships_properties(relationships_attributes)
    }
    schema[:data][:example][:relationships][model_type] = relationships_example(relationships_attributes)
  end

  schema.deep_merge!(model.additional_schema) if model.respond_to? :additional_schema

  schema
end