class Middleman::Autoprefixer::Extension::Rack

Rack middleware to look for CSS and apply prefixes.

Constants

INLINE_CSS_REGEX

Public Class Methods

new(app, options = {}) click to toggle source

Init @param [Class] app @param [Hash] options

# File lib/middleman-autoprefixer/extension.rb, line 34
def initialize(app, options = {})
  @app = app
  @middleman_app = options.fetch(:middleman_app)
  @config = options.fetch(:config)
  @inline = @config[:inline]
  @ignore = @config[:ignore]

  @processor = ::AutoprefixerRails::Processor.new({
    browsers: @config[:browsers] && Array(@config[:browsers]),
    add:      @config[:add],
    remove:   @config[:remove],
    grid:     @config[:grid],
    supports: @config[:supports],
    flexbox:  @config[:flexbox]
  })
end

Public Instance Methods

call(env) click to toggle source

Rack interface @param [Rack::Environmemt] env @return [Array]

# File lib/middleman-autoprefixer/extension.rb, line 54
def call(env)
  status, headers, response = @app.call(env)

  type = headers.fetch('Content-Type', 'application/octet-stream').split(';').first
  path = env['PATH_INFO']

  prefixed = process(response, type, path)

  if prefixed.is_a?(String)
    headers['Content-Length'] = prefixed.bytesize.to_s
    response = [prefixed]
  end

  [status, headers, response]
end

Private Instance Methods

extract_styles(response) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 93
def extract_styles(response)
  ::Middleman::Util.extract_response_text(response)
end
inline_html_content?(type, path) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 97
def inline_html_content?(type, path)
  type == 'text/html' && @inline
end
prefix(content, path = nil) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 82
def prefix(content, path = nil)
  @processor.process(content, path ? { from: path } : {}).css
rescue => e
  @middleman_app.logger.error(e.message)
  raise e
end
prefix_inline_styles(content) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 89
def prefix_inline_styles(content)
  content.gsub(INLINE_CSS_REGEX) { $1 << prefix($2) << $3 }
end
process(response, type, path) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 72
def process(response, type, path)
  if standalone_css_content?(type, path)
    prefix(extract_styles(response), path)
  elsif inline_html_content?(type, path)
    prefix_inline_styles(extract_styles(response))
  else
    nil
  end
end
standalone_css_content?(type, path) click to toggle source
# File lib/middleman-autoprefixer/extension.rb, line 101
def standalone_css_content?(type, path)
  type == 'text/css' && @ignore.none? { |ignore| ::Middleman::Util.path_match(ignore, path) }
end