Skip to content

Instantly share code, notes, and snippets.

@d3chapma
Created June 29, 2015 17:54
Show Gist options
  • Save d3chapma/e7b984e8de658f6f107c to your computer and use it in GitHub Desktop.
Save d3chapma/e7b984e8de658f6f107c to your computer and use it in GitHub Desktop.
HtmlToPrawn
module HtmlToPrawn
def self.convert(string)
tokens = string.scan(/<[^>]+>|[^<>]+/)
stack = []
output = ""
tokens.each do |token|
case token
when /<span/
output << convert_open_span(token, stack)
when /<\/span/
output << convert_close_span(stack)
else
output << token
end
end
output
end
def self.convert_open_span(token, stack)
if token.include? 'font-size:'
starting_point = token.index(":") + 1
ending_point = token.index("px") - 1
font_size = token[starting_point..ending_point]
stack << :font
"<font size='#{font_size}'>"
elsif token.include? 'color:'
starting_point = token.index("#") + 1
ending_point = token.index("\">") - 1
font_color = token[starting_point..ending_point]
stack << :color
"<color rgb='#{font_color.strip}'>"
else
stack << :empty
""
end
end
def self.convert_close_span(stack)
tag = stack.pop
tag != :empty ? "</#{tag}>" : ''
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment