Sha256: c70cc28a0bd59e2fa597ce069e6d1b51f5b6471d915846e3b759ba4bacb8ec32

Contents?: true

Size: 832 Bytes

Versions: 44

Compression:

Stored size: 832 Bytes

Contents

require "css_parser"

module Lookbook
  class StylesExtractor < Service
    STYLE_TAGS_REGEX = /<style(?:\s[^>]*)?>((?:(?!<\/style>).)*)<\/style>/m

    attr_reader :content

    def initialize(content)
      @content = content.to_s
    end

    def call
      styles = extract_styles(content)
      rest = strip_styles(content)
      [styles, rest]
    end

    protected

    def extract_styles(text)
      css_parser = ::CssParser::Parser.new
      text.scan(STYLE_TAGS_REGEX).flatten.map(&:strip).each do |css|
        css_parser.load_string!(css.strip)
      end

      styles = []
      css_parser.each_selector do |selector, declarations, specificity|
        styles << "#{selector} { #{declarations} }"
      end
      styles
    end

    def strip_styles(text)
      text.gsub(STYLE_TAGS_REGEX, "").strip
    end
  end
end

Version data entries

44 entries across 44 versions & 1 rubygems

Version Path
lookbook-2.3.4 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.3.3 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.3.2 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.3.0 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.2.2 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.2.1 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.2.0 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.1.1 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.1.0 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.5 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.4 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.3 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.2 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.1 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.0 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.0.rc.3 lib/lookbook/services/templates/styles_extractor.rb
lookbook-1.5.5 lib/lookbook/services/templates/styles_extractor.rb
lookbook-1.5.4 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.0.rc.2 lib/lookbook/services/templates/styles_extractor.rb
lookbook-2.0.0.rc.1 lib/lookbook/services/templates/styles_extractor.rb