Created
January 7, 2024 16:38
-
-
Save henvo/049ec33707b9c1338564a8909d140031 to your computer and use it in GitHub Desktop.
Simple Ruby DSL for HTML generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: false | |
# This is the class that implements the DSL. | |
class Interpreter | |
def run(&block) | |
# Next line calls the block in the context of the instance. | |
instance_eval(&block) | |
end | |
def method_missing(name, **args, &block) | |
tag(name, args, &block) | |
end | |
def respond_to_missing?(_name) | |
true | |
end | |
def tag(name, args, &block) | |
html = '' | |
html << "<#{name} #{args_to_string(args)}>" | |
html << block.call if block_given? | |
html << "</#{name}>" | |
end | |
def args_to_string(args) | |
args.map { |k, v| "#{k}='#{v}'" }.join(' ') | |
end | |
end | |
# Example usage | |
val = Interpreter.new.run do | |
div class: 'first' do | |
div class: 'second' do | |
h1 class: 'header' | |
a href: 'https://github.com/henvo', target: '_blank' do | |
'This is a link' | |
end | |
end | |
end | |
end | |
puts val | |
# Outputs: | |
# <div class='first'><div class='second'><a href='https://github.com/henvo' target='_blank'>This is a link</a></div></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment