Class: JSONAPI::Materializer::Resource::Relationship

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model
Defined in:
lib/jsonapi/materializer/resource/relationship.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**keyword_arguments) ⇒ Relationship

Returns a new instance of Relationship.



15
16
17
18
19
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 15

def initialize(**keyword_arguments)
  super(**keyword_arguments)

  validate!
end

Instance Attribute Details

#parentObject

Returns the value of attribute parent.



10
11
12
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 10

def parent
  @parent
end

Returns the value of attribute related.



9
10
11
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 9

def related
  @related
end

Instance Method Details

#as_jsonObject



21
22
23
24
25
26
27
28
29
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 21

def as_json(*)
  {
    data:,
    links: {
      self: links_self,
      related: links_related
    }
  }.transform_values(&:presence).compact
end

#dataObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 43

def data
  return if related_parent_materializer.blank?

  @data ||= if related.many?
              related_parent_materializer.map do |child|
                {
                  id: child.attribute("id").for(child).to_s,
                  type: child.type.to_s
                }
              end
            else
              {
                id: related_parent_materializer.attribute("id").for(related_parent_materializer).to_s,
                type: related_parent_materializer.type.to_s
              }
            end
end


37
38
39
40
41
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 37

def links_related
  Addressable::Template.new(
    "#{parent.links_self}/#{related.name}"
  ).pattern
end

rubocop:enable Metrics/AbcSize



62
63
64
# File 'lib/jsonapi/materializer/resource/relationship.rb', line 62

def related_parent_materializer
  related.for(parent)
end