Created
April 30, 2015 13:57
-
-
Save christophermlne/04291d8e2f275bd96a26 to your computer and use it in GitHub Desktop.
Toronto Ruby Brigate: DSL Workshop Solution, April 29 2015
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
class FancyMarkup | |
def initialize | |
end | |
def method_missing(name, attr={}, &block) | |
puts "<#{name}#{self.flatten(attr)}>" | |
self.instance_eval(&block) | |
puts "</#{name}>" | |
end | |
def flatten(h) | |
flat = '' | |
h.keys.each { |k| flat << " #{k}=\"#{h[k]}\"" } | |
flat | |
end | |
def div(attr= {}, &block) | |
if attr[:id] | |
puts "<div id=\"#{attr[:id]}\">" | |
else | |
puts "<div>" | |
end | |
self.instance_eval(&block) | |
puts "</div>" | |
end | |
def li(content = '', attr= {}, &block) | |
if attr[:class] | |
puts "<li class=\"#{attr[:class]}\">" | |
else | |
puts "<li>" | |
end | |
puts content | |
if block_given? | |
self.instance_eval(&block) | |
end | |
puts "</li>" | |
end | |
end | |
markup = FancyMarkup.new.html do | |
body do | |
div id: "container" do | |
ul class: "pretty" do | |
li "Item 1", class: :active | |
li "Item 2" | |
end | |
article class: 'foo', id: 'foofoo' do | |
foobar id: 'bar' do | |
end | |
end | |
end | |
end | |
end | |
p FancyMarkup.instance_methods false | |
# output: | |
# <html> | |
# <body> | |
# <div id="container"> | |
# <ul class="pretty"> | |
# <li class="active"> | |
# Item 1 | |
# </li> | |
# <li> | |
# Item 2 | |
# </li> | |
# </ul> | |
# <article class="foo" id="foofoo"> | |
# <foobar id="bar"> | |
# </foobar> | |
# </article> | |
# </div> | |
# </body> | |
# </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment