Module: CdnHelpers::HtmlRewriter
- Defined in:
- lib/cdn_helpers.rb
Class Method Summary collapse
- .process_asset_url(href, file_path, public_root_path, logger) ⇒ Object
- .process_document(html, file_path, public_root_path, asset_hosts, logger) ⇒ Object
- .rewrite_file(logger, file_path, public_root_path, asset_hosts) ⇒ Object
Class Method Details
.process_asset_url(href, file_path, public_root_path, logger) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/cdn_helpers.rb', line 49 def self.process_asset_url(href, file_path, public_root_path, logger) local_url = Pathname.new(href) url_prefix = "/" if local_url.relative? logger.warn "We don't yet support relative paths to assets: #{local_url}" return href else local_url = local_url.to_s[(url_prefix.length - 1)..-1] if local_url.to_s.index(url_prefix) == 0 file_path = public_root_path.join(local_url[1..-1]).cleanpath.relative_path_from(public_root_path).to_s end return "#{url_prefix[0..-2]}#{CdnHelpers::AssetPath.hash_file("/" + file_path, public_root_path, logger)}" end |
.process_document(html, file_path, public_root_path, asset_hosts, logger) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/cdn_helpers.rb', line 62 def self.process_document(html, file_path, public_root_path, asset_hosts, logger) to_handle = { "link[rel=stylesheet]" => "href", "script[src]" => "src", "img" => "src", 'link[rel="shortcut icon"]' => "href" } to_handle.each do |selector, attribute| html.search(selector).each do |elem| if URI.parse(elem[attribute]).scheme.nil? elem[attribute] = asset_hosts.sample + process_asset_url(elem[attribute], file_path, public_root_path, logger) end end end # The contents of any style elements should be processed as CSS files require 'stringio' html.search('style').each do |elem| pseudo_css_file = StringIO.new(elem.content) processed_css = CssRewriter.process_css_file(logger, pseudo_css_file, file_path, public_root_path, asset_hosts.sample + "/") elem.content = processed_css end html end |
.rewrite_file(logger, file_path, public_root_path, asset_hosts) ⇒ Object
42 43 44 45 46 47 |
# File 'lib/cdn_helpers.rb', line 42 def self.rewrite_file(logger, file_path, public_root_path, asset_hosts) html_content = open(file_path).read html = Nokogiri::HTML.parse(html_content) process_document(html, file_path, public_root_path, asset_hosts, logger) File.open(file_path, 'w') { |f| f << html.to_s } end |