Class: Blueprint::CSSParser

Inherits:
Object
  • Object
show all
Defined in:
lib/blueprint/css_parser.rb

Overview

Strips out most whitespace and can return a hash or string of parsed data

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(css_string = "", options = {}) ⇒ CSSParser

Options

  • css_string String of CSS data

  • options

    • :namespace – Namespace to use when generating output


11
12
13
14
15
# File 'lib/blueprint/css_parser.rb', line 11

def initialize(css_string = "", options = {})
  @raw_data     = css_string
  @namespace    = options[:namespace] || ""
  compress(@raw_data)
end

Instance Attribute Details

#css_outputObject (readonly)

Returns the value of attribute css_output


5
6
7
# File 'lib/blueprint/css_parser.rb', line 5

def css_output
  @css_output
end

#namespaceObject

Returns the value of attribute namespace


4
5
6
# File 'lib/blueprint/css_parser.rb', line 4

def namespace
  @namespace
end

#raw_dataObject (readonly)

Returns the value of attribute raw_data


5
6
7
# File 'lib/blueprint/css_parser.rb', line 5

def raw_data
  @raw_data
end

Instance Method Details

#parse(data = nil) ⇒ Object

returns a hash of all CSS data passed

Options

  • data – CSS string; defaults to string passed into the constructor


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/blueprint/css_parser.rb', line 26

def parse(data = nil)
  data ||= @raw_data

  # wrapper array holding hashes of css tags/rules
  css_out = []
  # clear initial spaces
  data.strip_side_space!.strip_space!

  # split on end of assignments
  data.split('}').each_with_index do |assignments, index|
    # split again to separate tags from rules
    tags, styles = assignments.split('{').map{|a| a.strip_side_space!}
    unless styles.blank?
      # clean up tags and apply namespaces as needed
      tags.strip_selector_space!
      tags.gsub!(/\./, ".#{namespace}") unless namespace.blank?

      # split on semicolon to iterate through each rule
      rules = []
      styles.split(";").each do |key_val_pair|
        unless key_val_pair.nil?
          # split by property/val and append to rules array with correct declaration
          property, value = key_val_pair.split(":", 2).map {|kv| kv.strip_side_space! }
          break unless property && value
          rules << "#{property}:#{value};"
        end
      end
      # now keeps track of index as hashes don't keep track of position
      # (which will be fixed in Ruby 1.9)
      unless tags.blank? || rules.to_s.blank?
        css_out << {:tags => tags, :rules => rules.join, :idx => index}
      end
    end
  end
  css_out
end

#to_sObject

returns string of CSS which can be saved to a file or otherwise


18
19
20
# File 'lib/blueprint/css_parser.rb', line 18

def to_s
  @css_output
end