Class: Avo::ItemGrapher

Inherits:
Object
  • Object
show all
Defined in:
lib/avo/item_grapher.rb

Overview

Use it like this: Avo::ItemGrapher.new(resource).render(view: :edit)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(item) ⇒ ItemGrapher

Returns a new instance of ItemGrapher.



6
7
8
# File 'lib/avo/item_grapher.rb', line 6

def initialize(item)
  @item = item
end

Instance Attribute Details

#itemObject (readonly)

Returns the value of attribute item.



4
5
6
# File 'lib/avo/item_grapher.rb', line 4

def item
  @item
end

Instance Method Details

#decode_item(item) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/avo/item_grapher.rb', line 10

def decode_item(item)
  result = ""
  result << "──" * (item[:level])
  result << ""
  result << item[:id]
  if item[:items].present?
    item[:items].each do |itm|
      result << "<br />"
      result << decode_item(itm)
    end

  end
  result
end

#render(**args) ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/avo/item_grapher.rb', line 70

def render(**args)
  result = unwrap(item, **args)
    .map do |item|
      decode_item(item)
    end
    .join("<br />")
  "<pre>#{result}</pre>".html_safe
end

#unwrap(i, level = 0, view: :show) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/avo/item_grapher.rb', line 25

def unwrap(i, level = 0, view: :show)
  result = []

  i.items.each do |item|
    label = ""
    label << item.class.name.demodulize
    label << " "
    if item.respond_to?(:name)
      label << "{#{item.name}}"
      label << " "
    end
    label << (item.hydrate(view: view).visible_in_view?(view: view) ? "visible" : "invisible")
    if item.class.ancestors.include?(Avo::Concerns::HasItems)
      if item.visible_items.present?
        label << " | HAS_ITEMS #{item.visible_items.count} items"
        # abort item.visible_items.inspect
        label << item.visible_items.map(&:class).inspect
      else
        label << " | DOES_NOT_HAVE_ITEMS"
      end
    end
    if item.respond_to?(:is_empty?)
      label << " "
      label << (item.is_empty? ? "[IS EMPTY!]" : "[#{item.visible_items.count}]")
    end
    payload = if item.respond_to?(:items) && item.items.present?
      {
        id: label,
        items: unwrap(item, level + 1),
      }
    else
      {
        id: label
      }
    end

    result << {
      **payload,
      level: level,
    }
  end

  result
end