Class: Fira::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/fira/engine.rb

Constant Summary collapse

ID_REGEX =
/ #([^0-9][a-z_A-Z0-9_\-]+)/
CLASS_REGEX =
/ \.([^0-9][a-z_A-Z0-9_\-]+)/
QUOTE_REGEX =
/\S+=["']?(?:.(?!["']?\s+(?:\S+)=|[>"']))+.["']?/
TAG_OPEN_REGEX =
/<[^\/%!]\w* /
TAG_END_REGEX =
/([\/]?>)/

Instance Method Summary collapse

Instance Method Details

#insert_quotes(_quotes, tag) ⇒ Object



70
71
72
73
74
75
# File 'lib/fira/engine.rb', line 70

def insert_quotes(_quotes, tag)
  space = ''
  space = ' ' if _quotes.length > 0
  quotes = _quotes.join(" ")
  tag.sub(TAG_END_REGEX, space + quotes + '\1')
end

#is_opening_tag?(text) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
80
# File 'lib/fira/engine.rb', line 77

def is_opening_tag?(text)
  val = text =~ TAG_OPEN_REGEX
  val.nil? || val > 0 ? false : true
end

#parse_classes(text) ⇒ Object



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

def parse_classes(text)
  #find fira class attributes
  classes = text.scan(CLASS_REGEX)

  if classes.empty?
    return text
  end

  #build an HTML class attribute
  att = 'class="'

  classes.each do |cl|
    att += " #{cl[0]}"
    text = text.sub(" ." + cl[0], "")
  end

  att += '"'

  #remove the space before the first class
  att = att.sub(/class=" /, ' class="')

  text.sub(TAG_END_REGEX, att + '\1')
end

#parse_text(text) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/fira/engine.rb', line 14

def parse_text(text)
  output = ""
  tokenizer = HTML::Tokenizer.new(text)
  while token = tokenizer.next

    #if it's an opening tag, analyze it
    if is_opening_tag?(token)

      #remove any quotes
      quotes = token.scan(QUOTE_REGEX)
      no_quotes = token.gsub(QUOTE_REGEX, '')

      #find and replace fira ID attributes
      result = no_quotes.sub(ID_REGEX, ' id="\1"')

      #find and replace fira class attributes
      result = parse_classes(result)

      #add back in the quotes
      output += insert_quotes(quotes, result)

      #find and replace fira data attributes
      output = output.gsub("\$", "data-")

    else
      output += token
    end
  end

  return output
end