-
-
Save sergii/6deaf68232a39f4200ecd9f84eac144b to your computer and use it in GitHub Desktop.
The Phlex::Element class makes creating simple Phlex components easier
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
require "bundler/inline" | |
gemfile do | |
source "https://rubygems.org" | |
gem "phlex" | |
end | |
require "phlex/testing/view_helper" | |
include Phlex::Testing::ViewHelper | |
module Phlex | |
class Element < HTML | |
def initialize(tag, **attributes) | |
@tag = tag | |
@attributes = attributes | |
end | |
def new(**attributes) | |
self.class.new(@tag, **@attributes.merge(attributes)) | |
end | |
def template(&) | |
self.send(@tag, **@attributes, &) | |
end | |
# Define a class method '[]' that accepts the tag and default attributes. | |
def self.[](tag, **default_attributes) | |
# Dynamically create a Class that inherits from Element. | |
Class.new(self) do | |
# Define an initialize method for this dynamic class. | |
define_method(:initialize) do |**attributes| | |
# Merge the default attributes with the provided attributes. | |
super(tag, **default_attributes.merge(attributes)) | |
end | |
end | |
end | |
end | |
end | |
InputTag = Phlex::Element.new(:input, type: :text, autofocus: true, required: true, class: "p-4") | |
p render InputTag.new(class: "p-12") | |
p render InputTag.new(class: "p-2") | |
class ClassicalInputTag < Phlex::Element[:input, type: :text, class: "p-4"] | |
def around_template | |
div(class: "foo") do | |
yield | |
end | |
end | |
end | |
p render ClassicalInputTag.new(class: "p-20") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment