Lesson 2 — Kits
The problem
Without Kits, rendering a component requires both render and .new:
|
|
As components are used inside other components this becomes repetitive. Kits give us a cleaner syntax.
Setting up the Kit
Add extend Phlex::Kit to base.rb:
|
|
extend Phlex::Kit turns the Components module into a Kit. Every component class defined under Components:: automatically gets a corresponding shorthand method. Instead of:
|
|
You can write:
|
|
And when you include Components inside another component, the namespace disappears entirely:
|
|
One gotcha: when a component takes no arguments and no block, use empty parentheses — Ruby needs them to know you are calling a method rather than looking up a constant:
1 2Components::Spinner() # method call — renders the component Components::Spinner # constant lookup — returns the class itself
Updating the demo page
Add include Components to DemoPage and replace the render ... .new(...) calls. From now on all demo examples use Kit syntax:
|
|
The output is identical — the Kit syntax is purely a call-site improvement.
Exercise
Update demo.rb as shown. Confirm that Heading(text: "Hello", level: 2) produces the same output as render Components::Heading.new(text: "Hello", level: 2) by printing both to the terminal before switching to Kit syntax.