Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active January 3, 2024 22:21
Show Gist options
  • Save bradgessler/07da71fdaff90f0948cd1a00abe5a87b to your computer and use it in GitHub Desktop.
Save bradgessler/07da71fdaff90f0948cd1a00abe5a87b to your computer and use it in GitHub Desktop.

Revisions

  1. bradgessler revised this gist Nov 9, 2023. No changes.
  2. bradgessler created this gist Nov 9, 2023.
    53 changes: 53 additions & 0 deletions phlex_element.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    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")