File: how-it-works.md

package info (click to toggle)
ruby-view-component 4.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,832 kB
  • sloc: ruby: 8,385; sh: 166; makefile: 4
file content (45 lines) | stat: -rw-r--r-- 1,352 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
---
layout: default
title: How it works
nav_order: 5
---

## How ViewComponent Works

### At application boot

When `ViewComponent::Base` is inherited from, `ViewComponent::Compiler.compile` compiles a component's template(s) into instance method(s) on the component:

```ruby
class MyComponent < ViewComponent::Base
end
```

```erb
<%= Time.now %>
```

Compiles to:

```ruby
class MyComponent < ViewComponent::Base
  def _call_my_component
    @output_buffer.append = (Time.now)
    @output_buffer
  end
end
```

### At component instantiation

Component initializer runs if defined. ViewComponent does not perform any actions.

### At render

When a ViewComponent is passed to `render`, Rails calls `render_in`, passing the current [ActionView::Context](https://api.rubyonrails.org/classes/ActionView/Context.html). `ActionView::Context` is used to provide access to the current controller, request, and helpers, which is why they cannot be referenced until a component is rendered.

First, ViewComponent calls the `before_render` method, which gives ViewComponents the opportunity to execute logic before render time but after initialization.

Second, ViewComponent calls `render?`, returning early with an empty string if `render?` returns false.

ViewComponent then renders the component template, wrapped in a call to the `around_render` method.