Last active
March 31, 2023 19:26
-
-
Save tangentus/841915628c07977e672e6ab3d51f65af to your computer and use it in GitHub Desktop.
A PoC of a Stimulus ViewComponent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= render StimulusComponent.new controller: "test" do |component| %> | |
<button <%= component.action :click, :test, :test %>>Hello, Stimulus Component!</button> | |
<% end %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="<%= controller.camelize %>" <%= initialize_controller %> <%= action_attributes %>> | |
<%= content %> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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