Class: Bridgetown::Resource::Relations

Inherits:
Object
  • Object
show all
Defined in:
bridgetown-core/lib/bridgetown-core/resource/relations.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource) ⇒ Relations

Returns a new instance of Relations.

Parameters:



15
16
17
18
19
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 15

def initialize(resource)
  @resource = resource
  @site = resource.site
  @inflector = site.config.inflector
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(type, *args) ⇒ Object



56
57
58
59
60
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 56

def method_missing(type, *args)
  return super unless type.to_s.within?(relation_types)

  resources_for_type(type)
end

Instance Attribute Details

#resourceBridgetown::Resource::Base (readonly)



9
10
11
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 9

def resource
  @resource
end

#siteBridgetown::Site (readonly)

Returns:



12
13
14
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 12

def site
  @site
end

Instance Method Details

#relation_schemaHashWithDotAccess::Hash



22
23
24
25
26
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 22

def relation_schema
  @relation_schema ||= resource.collection..relations&.transform_values do |value|
    value.is_a?(Array) ? value.map(&:to_s) : value.to_s
  end
end

#relation_typesArray<String>

Returns:

  • (Array<String>)


29
30
31
32
33
34
35
36
37
38
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 29

def relation_types
  @relation_types ||= begin
    types = []
    relation_schema&.each_value do |collections|
      types << collections
      types << Array(collections).map { |item| @inflector.pluralize(item) }
    end
    types.flatten.uniq
  end
end

#resources_for_type(type) ⇒ Bridgetown::Resource::Base+

Parameters:

  • type (Symbol)

Returns:



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 42

def resources_for_type(type)
  relation_kind = kind_of_relation_for_type(type)
  return [] unless relation_kind

  case relation_kind.to_sym
  when :belongs_to
    belongs_to_relation_for_type(type)
  when :has_many
    has_many_relation_for_type(type)
  when :has_one
    has_one_relation_for_type(type)
  end
end

#respond_to_missing?(type, *_args) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 62

def respond_to_missing?(type, *_args)
  type.to_s.within?(relation_types)
end

#to_liquidObject



66
67
68
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 66

def to_liquid
  @to_liquid ||= Drops::RelationsDrop.new(self)
end