Last active
November 25, 2024 17:37
-
-
Save rainerborene/cb8b1dbcf5789ca7945a25ad1026674c to your computer and use it in GitHub Desktop.
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
# frozen_string_literal: true | |
class ExampleComponent < MiniView | |
def template | |
button type: "button", class: [ | |
"inline-flex items-center gap-x-1.5 rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm", | |
"hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" | |
] do | |
plain "This works" | |
em do | |
span "nesting" | |
strong do | |
plain "also works" | |
end | |
end | |
end | |
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
# frozen_string_literal: true | |
class MiniView | |
undef :p | |
def self.tag_elements | |
@tag_elements ||= ActionView::Helpers::TagHelper::TagBuilder.instance_methods(false) | |
end | |
def template | |
raise NotImplementedError | |
end | |
def render_in(view_context) | |
raise ArgumentError, "#{self.class} does not support passing a block" if block_given? | |
@view_context = view_context | |
@view_context.with_output_buffer { template } | |
end | |
def plain(string) | |
@view_context.concat(string) | |
end | |
def method_missing(method, ...) | |
if self.class.tag_elements.include?(method) | |
@view_context.concat @view_context.tag.__send__(method, ...) | |
elsif @view_context.respond_to?(method, false) | |
@view_context.__send__(method, ...) | |
else | |
super | |
end | |
end | |
def respond_to_missing?(method, include_all = false) | |
return true if super | |
return true if self.class.tag_elements.include?(method) | |
@view_context.respond_to?(method, false) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment