From b47e92afa19c9cb13b76965ca44ce13b2c61879f Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Mon, 25 Nov 2024 01:33:48 +1300 Subject: [PATCH] Add convenient constructor. --- lib/live/element.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/live/element.rb b/lib/live/element.rb index ead3338..e31f099 100644 --- a/lib/live/element.rb +++ b/lib/live/element.rb @@ -16,18 +16,27 @@ def self.unique_id SecureRandom.uuid end + # Mount an element within a parent element. def self.mount(parent, id, data = {}) full_id = parent.id + ":" + id self.new(full_id, data) end + # Create a new element. + def self.[](id = self.unique_id, **data) + self.new(id, data) + end + + # Create a new element. + # # @parameter id [String] The unique identifier within the page. # @parameter data [Hash] The data associated with the element, typically stored as `data-` attributes. - def initialize(id = Element.unique_id, data = {}) + def initialize(id = self.class.unique_id, data = {}) + data[:class] ||= self.class.name + @id = id @data = data - @data[:class] ||= self.class.name @page = nil end