Class: TinyCss::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_css/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



5
6
7
# File 'lib/tiny_css/base.rb', line 5

def initialize
  @style = OrderedHash.new
end

Instance Attribute Details

#styleObject

Returns the value of attribute style.



3
4
5
# File 'lib/tiny_css/base.rb', line 3

def style
  @style
end

Instance Method Details

#read(file) ⇒ Object



9
10
11
# File 'lib/tiny_css/base.rb', line 9

def read(file)
  read_string open(file).read
end

#read_string(string) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tiny_css/base.rb', line 13

def read_string(string)
  string = string.tr("\n\t", '  ').gsub(%r!/\*.*?\*/!, '')

  split_by_closing_brace(string).reject { |v| v !~ /\S/ }.each do |v|
    unless match = v.match(/^\s*([^{]+?)\s*\{(.*)\}\s*$/)
      raise Error, "Invalid or unexpected style data '#{ v }'"
    end

    style = match.captures.first
    styles = style.gsub(/\s+/, ' ').split(/\s*,\s*/).
      reject { |v| v !~ /\S/ }

    match.captures.last.split(/\;/).reject { |v| v !~ /\S/ }.each do |v|
      unless match = v.match(/^\s*([\w._-]+)\s*:\s*(.*?)\s*$/)
        raise Error, "unexpected property '#{ v }' in style '#{ style }'"
      end
      styles.each do |v|
        @style[v][match.captures.first.downcase] = match.captures.last
      end
    end
  end

  self
end

#write(file, sort = true) ⇒ Object



38
39
40
# File 'lib/tiny_css/base.rb', line 38

def write(file, sort = true)
  open(file, 'w').write write_string(sort)
end

#write_string(sort = true) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tiny_css/base.rb', line 42

def write_string(sort = true)
  style = @style.dup
  contents = ''
  selectors = style.keys
  selectors.sort!.reverse! if sort
  selectors.each do |selector|
    contents += "#{ selector } {\n"
    keys = style[selector].keys
    keys.sort! if sort
    keys.each { |k| contents += "\t#{ k }: #{ @style[selector][k] };\n" }
    contents += "}\n"
  end

  contents
end