Module: Micra::Rails::ViewHelpers
- Defined in:
- lib/micra/rails/view_helpers.rb
Overview
View helpers for Micra.js components.
<%= micra_component :counter, count: 0 do %>
<button @click="dec">−</button>
<strong data-text="count"></strong>
<button @click="inc">+</button>
<% end %>
Produces:
<div data-component="counter" data-count="0">
<button @click="dec">−</button>
<strong data-text="count"></strong>
<button @click="inc">+</button>
</div>
Instance Method Summary collapse
-
#micra_component(name, tag: :div, **props, &block) ⇒ Object
Renders a wrapper <%= tag %> with ‘data-component=“<name>”` and `data-<key>=“<value>”` for each prop.
-
#micra_includes ⇒ Object
Drop into your application layout once.
-
#micra_state(**props) ⇒ Object
Inline JSON props for a single component instance.
Instance Method Details
#micra_component(name, tag: :div, **props, &block) ⇒ Object
Renders a wrapper <%= tag %> with ‘data-component=“<name>”` and `data-<key>=“<value>”` for each prop. Non-string values are JSON-encoded so they round-trip via this.prop() in Micra.
24 25 26 27 28 29 30 31 32 |
# File 'lib/micra/rails/view_helpers.rb', line 24 def micra_component(name, tag: :div, **props, &block) attributes = {"data-component" => name.to_s} props.each do |key, value| attributes["data-#{key.to_s.dasherize}"] = serialize_prop(value) end content_tag(tag, capture(&block), attributes) end |
#micra_includes ⇒ Object
Drop into your application layout once. Outputs the importmap module script that boots Micra and a final <script>Micra.start()</script>.
36 37 38 39 40 41 42 43 44 45 |
# File 'lib/micra/rails/view_helpers.rb', line 36 def micra_includes capture do concat concat javascript_tag(<<~JS, type: "module") import * as Micra from "micra" window.Micra = Micra document.addEventListener("DOMContentLoaded", () => Micra.start()) JS end end |
#micra_state(**props) ⇒ Object
Inline JSON props for a single component instance.
<%= micra_state user: @user.as_json %>
Equivalent to writing data-user=‘“id”:1,…’ yourself.
52 53 54 |
# File 'lib/micra/rails/view_helpers.rb', line 52 def micra_state(**props) props.map { |k, v| ["data-#{k.to_s.dasherize}", serialize_prop(v)] }.to_h end |