Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active January 3, 2024 22:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bradgessler/07da71fdaff90f0948cd1a00abe5a87b to your computer and use it in GitHub Desktop.
Save bradgessler/07da71fdaff90f0948cd1a00abe5a87b to your computer and use it in GitHub Desktop.
The Phlex::Element class makes creating simple Phlex components easier
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