Class: WCC::Contentful::LinkVisitor

Inherits:
Object
  • Object
show all
Defined in:
lib/wcc/contentful/link_visitor.rb

Overview

The LinkVisitor is a utility class for walking trees of linked entries. It is used internally by the Store layer to compose the resulting resolved hashes. But you can use it too!

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(entry, *fields, depth: 0) ⇒ LinkVisitor

Returns a new instance of LinkVisitor.

Parameters:

  • entry (Hash)

    The entry hash (resolved or unresolved) to walk

  • The (Array<Symbol>)

    type of fields to select from the entry tree. Must be one of ‘:Link`, `:Entry`, `:Asset`.

  • depth (Fixnum) (defaults to: 0)

    (optional) How far to walk down the tree of links. Be careful of recursive trees!



14
15
16
17
18
19
20
21
22
# File 'lib/wcc/contentful/link_visitor.rb', line 14

def initialize(entry, *fields, depth: 0)
  unless entry.is_a?(Hash) && entry.dig('sys', 'type') == 'Entry'
    raise ArgumentError, "Please provide an entry as a hash value (got #{entry})"
  end

  @entry = entry
  @fields = fields.map(&:to_s)
  @depth = depth
end

Instance Attribute Details

#depthObject (readonly)

Returns the value of attribute depth.



7
8
9
# File 'lib/wcc/contentful/link_visitor.rb', line 7

def depth
  @depth
end

#entryObject (readonly)

Returns the value of attribute entry.



7
8
9
# File 'lib/wcc/contentful/link_visitor.rb', line 7

def entry
  @entry
end

#fieldsObject (readonly)

Returns the value of attribute fields.



7
8
9
# File 'lib/wcc/contentful/link_visitor.rb', line 7

def fields
  @fields
end

Instance Method Details

#each {|value, field, locale| ... } ⇒ Object

Walks an entry and its resolved links, without transforming the entry.

Yields:

  • (value, field, locale)

Yield Parameters:



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/wcc/contentful/link_visitor.rb', line 30

def each(&block)
  _each do |val, field, locale, index|
    yield(val, field, locale, index) if should_yield_field?(field, val)

    next unless should_walk_link?(field, val)

    self.class.new(val, *fields, depth: depth - 1).each(&block)
  end

  nil
end

#map!(&block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/wcc/contentful/link_visitor.rb', line 42

def map!(&block)
  _each do |val, field, locale, index|
    if should_yield_field?(field, val)
      val = yield(val, field, locale, index)
      set_field(field, locale, index, val)
    end

    next unless should_walk_link?(field, val)

    self.class.new(val, *fields, depth: depth - 1).map!(&block)
  end

  entry
end