Created
January 11, 2011 03:05
-
-
Save justinko/773952 to your computer and use it in GitHub Desktop.
Create an HTML table in Ruby
This file contains hidden or 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
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