Sha256: 9135582a21d8eea308af31687a208a8af9389d6c13b00dbf4bd944d59f4e5f9d

Contents?: true

Size: 1.5 KB

Versions: 4

Compression:

Stored size: 1.5 KB

Contents

require "beautiful-css/rule_parser"
require "sass"

module BeautifulCss
  class Engine

    def initialize input
      @input = input
    end

    def scss_to_css scss
      Sass::Engine.new(scss,{:syntax => :scss}).render
    end

    def to_s
      render
    end

    def render
      return nil if @input.nil?
      rules = build_rules
      cleaned = remove_unset rules
      groups = build_groups(cleaned)
      return format( groups )
    end


    private

    def build_rules
      text = scss_to_css @input
      text = text.gsub( /[\n\r\t]/m, " " )
      text = text.gsub( / +/m, " " )
      text = text.gsub( /\/\*[^*]*\*\//m, " " )
      rules = text.split('}')
      rules = rules.map{|r| RuleParser.new(r).to_rules }.flatten
    end

    def remove_unset rules
      hash = {}
      rules.each do |r|
        hash[r.prop] = {} if !( hash.has_key? r.prop)
        hash[r.prop][r.selector] = r.value
      end
      hash
    end

    def build_groups rules
      groups = {}
      rules.keys.each do |prop|
        rules[prop].keys.each do |selector|
          val = rules[prop][selector]
          prop_val = "{ #{prop}:#{val} }"
          groups[prop_val] = [] if !( groups.has_key? prop_val)
          groups[prop_val] << selector
        end
      end
      groups
    end

    def format groups
      output = ''
      groups.keys.sort.each do |key|
        output += "\n"
        output += groups[key].uniq.join(",\n") + "\n"
        output += key + "\n"
      end
      output.gsub( /: +/, ':' )
    end


  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
beautiful-css-0.0.8 lib/beautiful-css/engine.rb
beautiful-css-0.0.6 lib/beautiful-css/engine.rb
beautiful-css-0.0.5 lib/beautiful-css/engine.rb
beautiful-css-0.0.4 lib/beautiful-css/engine.rb