Skip to content

Instantly share code, notes, and snippets.

@justinko
Created January 11, 2011 03:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save justinko/773952 to your computer and use it in GitHub Desktop.
Save justinko/773952 to your computer and use it in GitHub Desktop.
Create an HTML table in Ruby
html = "".tap do |str|
str << '<table>'
str << '<tr>'
str << '<td>'
str << 'a'
str << '</td>'
str << '<td>'
str << 'b'
str << '</td>'
str << '</tr>'
str << '</table>'
end
puts html
module HTMLMethods
def wrap(tag)
concat "<#{tag}>"
yield
concat "</#{tag}>"
end
end
html = "".tap do |s|
s.extend HTMLMethods
s.wrap :table do
s.wrap :tr do
s.wrap(:td) { s << 'a' }
s.wrap(:td) { s << 'b' }
end
end
end
puts html
class HTMLFactory
def self.make(&block)
new.instance_eval(&block)
end
attr_reader :str
def initialize
@str = ""
end
def wrap(tag)
str.concat "<#{tag}>"
yield
str.concat "</#{tag}>"
end
end
html = HTMLFactory.make do
wrap :table do
wrap :tr do
wrap(:td) { str << 'a' }
wrap(:td) { str << 'b' }
end
end
end
puts html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment