Skip to content

Commit

Permalink
Attribute values > to_phlex_attribute_value, to_str, to_s (#629)
Browse files Browse the repository at this point in the history
Fixes #569 

Attribute values can be any object that responds to
`to_phlex_attribute_value` or `to_str`, falling back to `to_s` if
neither is defined.

Signed-off-by: Joel Drapper <joel@drapper.me>
Co-authored-by: Joel Drapper <joel@drapper.me>
  • Loading branch information
joelmoss and joeldrapper committed Jan 30, 2024
1 parent c610589 commit a910442
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
32 changes: 30 additions & 2 deletions gd/phlex/sgml/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,21 @@

include TestHelper

class ToPhlexAttributeValueable
def to_phlex_attribute_value
"to_phlex_attribute_value"
end
end

class ToSable
def to_s
"to_s"
end
end

class ToStrable
def to_str
"foo"
"to_str"
end
end

Expand Down Expand Up @@ -40,12 +52,28 @@ def to_str
expect(component.new).to_render %(<div class="bg-red-500 rounded"></div>)
end

test "with a to_phlex_attribute_value-able object" do
component = build_component_with_template do
div class: ToPhlexAttributeValueable.new
end

expect(component.new).to_render %(<div class="to_phlex_attribute_value"></div>)
end

test "with a to_s-able object" do
component = build_component_with_template do
div class: ToSable.new
end

expect(component.new).to_render %(<div class="to_s"></div>)
end

test "with a to_str-able object" do
component = build_component_with_template do
div class: ToStrable.new
end

expect(component.new).to_render %(<div class="foo"></div>)
expect(component.new).to_render %(<div class="to_str"></div>)
end

test "with numeric integer/float" do
Expand Down
10 changes: 9 additions & 1 deletion lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,15 @@ def __build_attributes__(attributes, buffer:)
when Set
buffer << " " << name << '="' << Phlex::Escape.html_escape(v.to_a.compact.join(" ")) << '"'
else
buffer << " " << name << '="' << Phlex::Escape.html_escape(v.to_str) << '"'
value = if v.respond_to?(:to_phlex_attribute_value)
v.to_phlex_attribute_value
elsif v.respond_to?(:to_str)
v.to_str
else
v.to_s
end

buffer << " " << name << '="' << Phlex::Escape.html_escape(value) << '"'
end
end

Expand Down

0 comments on commit a910442

Please sign in to comment.