Sha256: 043a4206a5e031cfdabcf488be1fc09dd6e32ac04233c7c9d4ad4ac6431398e1

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

module PremailerRails
  module CSSHelper
    extend self

    @@css_cache = {}

    def css_for_doc(doc)
      css = doc.search('link[@type="text/css"]').map { |link|
              url = link.attributes['href']
              load_css_at_path(url) unless url.blank?
            }.reject(&:blank?).join("\n")
      css = load_css_at_path(:default) if css.blank?
      css
    end

    private

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

      # Don't cache in development.
      if Rails.env.development? or not @@css_cache.include? path
        @@css_cache[path] =
          if defined? Hassle and Rails.configuration.middleware.include? Hassle
            file = path == :default ? '/stylesheets/email.css' : path
            File.read("#{Rails.root}/tmp/hassle#{file}")
          elsif assets_enabled?
            file = if path == :default
                     'email.css'
                   else
                     path.sub("#{Rails.configuration.assets.prefix}/", '')
                   end
            if asset = Rails.application.assets.find_asset(file)
              asset.to_s
            else
              raise "Couldn't find asset #{file} for premailer-rails3."
            end
          else
            file = path == :default ? '/stylesheets/email.css' : path
            File.read("#{Rails.root}/public#{file}")
          end
      end

      @@css_cache[path]
    rescue => ex
      # Print an error and store empty string as the CSS.
      puts ex.message
      @@css_cache[path] = ''
    end

    def assets_enabled?
      Rails.configuration.assets.enabled rescue false
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
premailer-rails3-1.0.2 lib/premailer-rails3/css_helper.rb