Skip to content

Commit

Permalink
Add support for unique id generation. Tests for Live::Element.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed May 4, 2024
1 parent 0d48cf4 commit 9170c62
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/live/element.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
# Copyright, 2021-2024, by Samuel Williams.

require 'json'
require 'securerandom'

module Live
# Represents a single dynamic content area on the page.
class Element
def self.unique_id
SecureRandom.uuid
end

# @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, **data)
def initialize(id = Element.unique_id, **data)
@id = id
@data = data
@data[:class] ||= self.class.name
Expand All @@ -21,6 +26,9 @@ def initialize(id, **data)
# The unique id within the bound page.
attr :id

# The data associated with the element.
attr :data

# Generate a JavaScript string which forwards the specified event to the server.
# @parameter details [Hash] The details associated with the forwarded event.
def forward_event(details = nil)
Expand Down
32 changes: 32 additions & 0 deletions test/live/element.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2024, by Samuel Williams.

require 'live/element'

describe Live::Element do
it "can generate a unique id" do
expect(Live::Element.unique_id).to be_a(String)

ids = 10.times.map do
Live::Element.unique_id
end

expect(ids.uniq.size).to be == ids.size
end

it "can be initialized with an id and data" do
element = subject.new("test", name: "Test")

expect(element.id).to be == "test"
expect(element.data[:name]).to be == "Test"
end

it "can be initialized with a default class" do
element = subject.new

expect(element.id).to be_a(String)
expect(element.data[:class]).to be == "Live::Element"
end
end
5 changes: 5 additions & 0 deletions test/live/website.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2024, by Samuel Williams.

require 'sus/fixtures/async/http/server_context'
require 'sus/fixtures/async/webdriver/session_context'

Expand Down

0 comments on commit 9170c62

Please sign in to comment.