Skip to content

Instantly share code, notes, and snippets.

@tangentus
Last active March 31, 2023 19:26
Show Gist options
  • Save tangentus/841915628c07977e672e6ab3d51f65af to your computer and use it in GitHub Desktop.
Save tangentus/841915628c07977e672e6ab3d51f65af to your computer and use it in GitHub Desktop.
A PoC of a Stimulus ViewComponent
<%= render StimulusComponent.new controller: "test" do |component| %>
<button <%= component.action :click, :test, :test %>>Hello, Stimulus Component!</button>
<% end %>
<div class="<%= controller.camelize %>" <%= initialize_controller %> <%= action_attributes %>>
<%= content %>
</div>
class StimulusComponent < BaseComponent
include Stimulus::Dsl
def initialize(controller:, actions: [])
@controller = controller
@actions = actions
end
private
attr_reader :controller, :actions
def action_attributes
action_string = ""
actions.each do |action_details|
action_string += action(action_details[:event_type], action_details[:controller], action_details[:controller_method])
end
action_string
end
def controller_id
controller.underscore
end
def controller_class
"#{controller.camelize}"
end
end
module Stimulus
module Dsl
def initialize_controller
"data-controller=#{controller}"
end
def action(event_type, controller, controller_method)
"data-action=#{event_type}->#{controller.to_s.underscore}##{controller_method}"
end
def data_target(controller, property)
"data-target=#{controller}.#{property}"
end
def data_attribute(attribute, value)
"data-content-#{dasherize(attribute)}=#{value}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment