Class: CSSInliner::Extractor

Inherits:
Object
  • Object
show all
Defined in:
lib/css_inliner/extractor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, directory) ⇒ Extractor

Returns a new instance of Extractor.



36
37
38
# File 'lib/css_inliner/extractor.rb', line 36

def initialize(document, directory)
  @document, @basedir = document, directory
end

Instance Attribute Details

#documentObject (readonly)

Returns the value of attribute document.



34
35
36
# File 'lib/css_inliner/extractor.rb', line 34

def document
  @document
end

Instance Method Details

#basedirObject



85
86
87
88
# File 'lib/css_inliner/extractor.rb', line 85

def basedir
  base = @document.css('base')
  base.empty? ? @basedir : base[0]['href']
end

#extract(remove_link_and_style = true) ⇒ Object



40
41
42
43
44
45
# File 'lib/css_inliner/extractor.rb', line 40

def extract(remove_link_and_style = true)
  sources = []
  sources.concat extract_from_link(remove_link_and_style)
  sources.concat extract_from_style(remove_link_and_style)
  integrate sources
end


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/css_inliner/extractor.rb', line 47

def extract_from_link(remove_link_element = true)
  group = nil
  @document.css('link').inject([]) do |sources, link|
    next sources unless link['rel'] == 'stylesheet'
    title = link['title']
    if title
      if group.nil?
        group = title
      elsif title != group
        next sources
      end
    end
    begin
      # To do: detect file encoding before open it(read only @charset value)
      open(File.join(basedir, link['href']), 'r:BOM|UTF-8') {|f| sources << f.read}
    rescue Errno::ENOENT
      warn File.join(basedir, link['href']) + ' not found'
    end
    link.remove if remove_link_element
    sources
  end
end

#extract_from_style(remove_style_element = true) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/css_inliner/extractor.rb', line 70

def extract_from_style(remove_style_element = true)
  @document.css('style').inject([]) do |sources, style|
    sources << style.content
    style.remove if remove_style_element
    sources
  end
end

#integrate(*sources) ⇒ Object



78
79
80
81
82
83
# File 'lib/css_inliner/extractor.rb', line 78

def integrate(*sources)
  source = sources.collect {|src| src * $RS}.join($RS)
  source = 'book {}' if source.empty?
  handler = CSSDocumentHandler.new
  CSSPool::SAC::Parser.new(handler).parse(source)
end