Class: Markbridge::Renderers::Discourse::RenderContext

Inherits:
Object
  • Object
show all
Defined in:
lib/markbridge/renderers/discourse/render_context.rb

Overview

Immutable context for rendering that wraps the parent chain Provides query methods to ask about parent elements without the renderer knowing about specific element types

Uses a hash-based cache for O(1) parent lookups instead of O(depth) scans

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parents = [], parent_cache: nil) ⇒ RenderContext

Returns a new instance of RenderContext.



14
15
16
17
18
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 14

def initialize(parents = [], parent_cache: nil)
  @parents = parents.freeze
  @depth = parents.size
  @parent_cache = parent_cache || build_cache(parents)
end

Instance Attribute Details

#depthObject (readonly)

Returns the value of attribute depth.



12
13
14
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 12

def depth
  @depth
end

#parentsObject (readonly)

Returns the value of attribute parents.



12
13
14
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 12

def parents
  @parents
end

Instance Method Details

#count_parents(klass) ⇒ Integer

Count parents of given type O(1) instead of O(depth)

Parameters:

  • klass (Class)

Returns:

  • (Integer)


48
49
50
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 48

def count_parents(klass)
  @parent_cache[klass]&.size || 0
end

#find_parent(klass) ⇒ AST::Element?

Find closest parent of given type O(1) hash lookup instead of O(depth) scan

Parameters:

  • klass (Class)

Returns:



40
41
42
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 40

def find_parent(klass)
  @parent_cache[klass]&.last
end

#has_parent?(klass) ⇒ Boolean

Check if parent of type exists O(1) check

Parameters:

  • klass (Class)

Returns:

  • (Boolean)


56
57
58
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 56

def has_parent?(klass)
  @parent_cache.key?(klass) && !@parent_cache[klass].empty?
end

#root?Boolean

Check if we’re at the root (no parents)

Returns:

  • (Boolean)


62
63
64
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 62

def root?
  @depth.zero?
end

#with_parent(element) ⇒ RenderContext

Create new context with element added to parent chain Incrementally updates cache instead of rebuilding from scratch

Parameters:

Returns:



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/markbridge/renderers/discourse/render_context.rb', line 24

def with_parent(element)
  new_parents = @parents + [element]

  # Incrementally update cache instead of rebuilding
  new_cache = @parent_cache.dup
  element_class = element.class
  new_cache[element_class] ||= []
  new_cache[element_class] = new_cache[element_class] + [element]

  self.class.new(new_parents, parent_cache: new_cache)
end