Class: Charming::Presentation::TemplateView

Inherits:
View
  • Object
show all
Defined in:
lib/charming/presentation/template_view.rb

Overview

TemplateView wraps a resolved ERB template and exposes it as a renderable View. The template is rendered with the view’s helpers (‘text`, `box`, `row`, `column`, `style`, `theme`, etc.) and the view’s assigns available as reader methods inside the template.

Instance Method Summary collapse

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(template:, namespace: nil, **assigns) ⇒ TemplateView

Returns a new instance of TemplateView.



9
10
11
12
13
# File 'lib/charming/presentation/template_view.rb', line 9

def initialize(template:, namespace: nil, **assigns)
  super(**assigns)
  @template = template
  @namespace = namespace
end

Instance Method Details

#renderObject

Renders the wrapped template to a string, evaluated in the view’s binding context.



16
17
18
# File 'lib/charming/presentation/template_view.rb', line 16

def render
  template.render(self).to_s
end

#template_bindingObject

Returns the binding used by ERB handlers to evaluate the template body. When namespace is set, the binding is created by a proc generated in the namespace’s context so the template can resolve constants relative to the application.



23
24
25
26
27
# File 'lib/charming/presentation/template_view.rb', line 23

def template_binding
  return binding unless namespace

  namespace.module_eval("->(view) { view.instance_eval { binding } }", __FILE__, __LINE__).call(self)
end