Created
February 17, 2009 19:06
-
-
Save sunny/65908 to your computer and use it in GitHub Desktop.
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
# Helper that adds inline CSS styles to the tags you want from an html string. | |
# Examples: | |
# add_styles("<p>Ohi</p>", :p => 'color:red') # => '<p style="color:red">Ohi</p>' | |
# add_styles("<p>Ohi</p>", :p => {:color => 'red'}) # => '<p style="color:red">Ohi</p>' | |
def add_styles(html, tags) | |
html = html.dup | |
tags.each do |tag, style| | |
style = style.map{|k,v| "#{k}:#{v}"}.join(';') unless style.is_a?(String) | |
html.gsub! /<(#{tag}.*?)(?: style="(.*?)")?(.*?)>/, | |
"<\\1 style=\"#{style};\\2\"\\3>" | |
end | |
html | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment