Class: Phlexing::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/phlexing/parser.rb

Class Method Summary collapse

Class Method Details

.call(source) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/phlexing/parser.rb', line 7

def self.call(source)
  source = ERBTransformer.call(source)
  source = Minifier.call(source)

  # Credit:
  # https://github.com/spree/deface/blob/6bf18df76715ee3eb3d0cd1b6eda822817ace91c/lib/deface/parser.rb#L105-L111
  #

  html_tag = /<html(( .*?(?:(?!>)[\s\S])*>)|>)/i
  head_tag = /<head(( .*?(?:(?!>)[\s\S])*>)|>)/i
  body_tag = /<body(( .*?(?:(?!>)[\s\S])*>)|>)/i

  if source =~ html_tag
    Nokogiri::HTML::Document.parse(source)
  elsif source =~ head_tag && source =~ body_tag
    Nokogiri::HTML::Document.parse(source).css("html").first
  elsif source =~ head_tag
    Nokogiri::HTML::Document.parse(source).css("head").first
  elsif source =~ body_tag
    Nokogiri::HTML::Document.parse(source).css("body").first
  else
    Nokogiri::HTML::DocumentFragment.parse(source)
  end
end