Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Webrat monkey patch so save_and_open_page can use stylesheets
module Webrat
module SaveAndOpenPage
def save_and_open_page
return unless File.exist?(Webrat.configuration.saved_pages_dir)
filename = "#{Webrat.configuration.saved_pages_dir}/webrat-#{Time.now.to_i}.html"
File.open(filename, "w") do |f|
f.write prettified(response_body)
end
open_in_browser(filename)
end
def prettified(response_html)
inline_css(response_html)
rewrite_image_and_js_references(response_html)
end
def inline_css(response_html)
remove_conditional_ie(response_html)
insert_css(response_html)
remove_stylesheet_references(response_html)
end
def remove_conditional_ie(response_html)
response_html.gsub!(/<!--\[.*?\]-->/im, '')
end
def remove_stylesheet_references(response_html)
response_html.gsub!(/<link href=(.*)\/>/i, '')
end
def rewrite_image_and_js_references(response_html)
response_html.gsub!(/("|')\/(images|javascripts)/, '\1' + '../public' + '/\2')
end
def insert_css(response_html)
response_html.gsub!(/<\/head>/, "<style>#{rewrite_css_image_references(response_html)}<\/style>\n<\/head>")
end
def rewrite_css_image_references(response_html)
css_files(response_html).map do |file|
content = File.read("public/stylesheets/#{file}.css")
content.gsub(/\/images/, "../public/images")
end.join("\n")
end
def css_files(response_html)
response_html.scan(/\<link href=".*stylesheets\/([^"]*).css/).flatten
end
end
end
Owner

duff commented Sep 21, 2011

Incorporated some changes from Jon Kinney:
http://jonkinney.com/articles/2010/04/21/using-save_and_open_page-to-open-failed-cucumber-scenerios-in-a-browser-with-images-and-css/

In particular, the idea of inlining the css to handle image filenames there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment