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



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

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
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 22

def relation_schema
  resource.collection..relations
end

#relation_typesArray<String>

Returns:

  • (Array<String>)


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

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:



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

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)


60
61
62
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 60

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

#to_liquidObject



64
65
66
# File 'bridgetown-core/lib/bridgetown-core/resource/relations.rb', line 64

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