Class: Bridgetown::Resource::Relations

Inherits:
Object
  • Object
show all
Defined in:
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:



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

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(type, *args) ⇒ Object



51
52
53
54
55
# File 'lib/bridgetown-core/resource/relations.rb', line 51

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

  resources_for_type(type)
end

Instance Attribute Details

#resourceBridgetown::Resource::Base (readonly)



7
8
9
# File 'lib/bridgetown-core/resource/relations.rb', line 7

def resource
  @resource
end

#siteBridgetown::Site (readonly)

Returns:



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

def site
  @site
end

Instance Method Details

#relation_schemaHashWithDotAccess::Hash



19
20
21
# File 'lib/bridgetown-core/resource/relations.rb', line 19

def relation_schema
  resource.collection..relations
end

#relation_typesArray<String>

Returns:

  • (Array<String>)


24
25
26
27
28
29
30
31
32
33
# File 'lib/bridgetown-core/resource/relations.rb', line 24

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

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

Parameters:

  • type (Symbol)

Returns:



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

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)


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

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

#to_liquidObject



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

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