Generators
LiveCable provides a Rails generator to quickly scaffold new components.
Usage
bin/rails generate live_cable:component NAME [options]This creates:
- A component class in
app/live/ - A view template in
app/views/live/
Basic Component
bin/rails generate live_cable:component counterGenerates:
app/live/counter.rb:
module Live
class Counter < LiveCable::Component
end
endapp/views/live/counter.html.live.erb:
<div>
</div>Options
--reactive
Define reactive variables with optional types. Supported types: integer, string, boolean, array, hash. Unrecognized or omitted types default to nil.
bin/rails generate live_cable:component counter --reactive count:integer name:string active:boolean items:array data:hash otherGenerates:
module Live
class Counter < LiveCable::Component
reactive :count, -> { 0 }
reactive :name, -> { "" }
reactive :active, -> { false }
reactive :items, -> { [] }
reactive :data, -> { {} }
reactive :other, -> { nil }
end
end--actions
Define action methods with stubs:
bin/rails generate live_cable:component counter --actions increment decrementGenerates:
module Live
class Counter < LiveCable::Component
actions :increment, :decrement
def increment
end
def decrement
end
end
end--compound
Generate a compound component with a directory-based template structure:
bin/rails generate live_cable:component wizard --compoundThis creates the view at app/views/live/wizard/component.html.live.erb instead of app/views/live/wizard.html.live.erb, and adds the compound declaration to the component class.
Combining Options
Options can be combined to scaffold a full component in one command:
bin/rails generate live_cable:component counter --reactive count:integer step:integer --actions increment decrement reset --compoundGenerates:
module Live
class Counter < LiveCable::Component
compound
reactive :count, -> { 0 }
reactive :step, -> { 0 }
actions :increment, :decrement, :reset
def increment
end
def decrement
end
def reset
end
end
endNamespaced Components
Use a slash-separated name to generate namespaced components:
bin/rails generate live_cable:component chat/message --reactive body:stringGenerates:
app/live/chat/message.rb:
module Live
module Chat
class Message < LiveCable::Component
reactive :body, -> { "" }
end
end
endapp/views/live/chat/message.html.live.erb:
<div>
</div>