Sha256: f5fa7434078e30d352ba50b79d6f80017e665ef0ba0024cf98c01ee51e782db8

Contents?: true

Size: 1.31 KB

Versions: 2

Compression:

Stored size: 1.31 KB

Contents

require 'open-uri'
require 'zlib'

class Premailer
  module Rails
    module CSSHelper
      extend self

      @cache = {}
      attr :cache

      STRATEGIES = [
        CSSLoaders::CacheLoader,
        CSSLoaders::AssetPipelineLoader,
        CSSLoaders::FileSystemLoader
      ]

      # Returns all linked CSS files concatenated as string.
      def css_for_doc(doc)
        urls = css_urls_in_doc(doc)
        urls.map { |url| load_css(url) }.join("\n")
      end

      private

      def css_urls_in_doc(doc)
        doc.search('link[@type="text/css"]').map do |link|
          link.attributes['href'].to_s
        end
      end

      def has_inline_css?(doc)
        not doc.search('style[@type="text/css"]').empty?
      end

      def load_css(url)
        path = extract_path(url)

        @cache[path] = STRATEGIES.each do |strategy|
                         css = strategy.load(path)
                         break css if css
                       end
      end

      # Extracts the path of a url.
      def extract_path(url)
        if url.is_a? String
          # Remove everything after ? including ?
          url = url[0..(url.index('?') - 1)] if url.include? '?'
          # Remove the host
          url = url.sub(/^https?\:\/\/[^\/]*/, '') if url.index('http') == 0
        end

        url
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
premailer-rails3-1.3.2 lib/premailer/rails/css_helper.rb
premailer-rails-1.3.2 lib/premailer/rails/css_helper.rb