Skip to content

Commit

Permalink
Add dynamic tag method (#748)
Browse files Browse the repository at this point in the history
Closes #707 

This provides a safer alternative to using `send` and `public_send` to
dynamically call Phlex methods when using your own meta-programming.
  • Loading branch information
joeldrapper authored Sep 2, 2024
2 parents 29eb1e4 + bd0f82e commit 74f8eb6
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,38 @@ def capture(*args, &block)
end
end

def tag(name, ...)
normalized_name = case name
when Symbol then name.name.downcase
when String then name.downcase
else raise ArgumentError.new("Expected the tag name as a Symbol or String.")
end

if normalized_name == "script"
raise ArgumentError.new("You can’t use the `<script>` tag from the `tag` method. Use `unsafe_tag` instead, but be careful if using user input.")
end

if registered_elements[normalized_name]
public_send(normalized_name, ...)
else
raise ArgumentError.new("Unknown tag: #{normalized_name}")
end
end

def unsafe_tag(name, ...)
normalized_name = case name
when Symbol then name.name.downcase
when String then name.downcase
else raise ArgumentError.new("Expected the tag name as a Symbol or String.")
end

if registered_elements[normalized_name]
public_send(normalized_name, ...)
else
raise ArgumentError.new("Unknown tag: #{normalized_name}")
end
end

private

# @api private
Expand Down

0 comments on commit 74f8eb6

Please sign in to comment.