Class: EasyFormat

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

Class Method Summary collapse

Class Method Details

.escape_html(text) ⇒ Object



68
69
70
# File 'lib/easy_format.rb', line 68

def self.escape_html(text)
  text.gsub(/[<]/,'&lt;').gsub(/[>]/,'&gt;')
end

.format(text, break_lines = true) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/easy_format.rb', line 6

def self.format(text, break_lines=true)
  return "" if text.nil?
  text = text.to_s
  text.strip!
  output = Array.new
  lines = text.split($/)
  for line in lines
    line = escape_html(line)
    line = replace_tabs(line)
    line.strip!
    line = link_urls(line)
    output.push(line)
  end
  connector = break_lines ? "<br/>\n" : " "
  output.join(connector)
end


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/easy_format.rb', line 30

def self.link_urls(text)
  protocols = ['http:','https:']
  for protocol in protocols
    re = Regexp.new(protocol+'(\S+)')
    if text =~ re
      md = re.match(text)
      url, ending = strip_last_punctuation(md[1])
      after = md.post_match
      if after =~ re
        after = link_urls(after)
      end
      output = md.pre_match
      url = protocol+url
      output += '<a class="external" href="'+url+'" title="'+url+'">'+url+'</a>'
      output += ending
      output += after
      text = output
    end
  end
  text
end

.replace_tabs(line) ⇒ Object



23
24
25
26
27
28
# File 'lib/easy_format.rb', line 23

def self.replace_tabs(line)
  tabbed = line.split(/\t/)
  output = tabbed.join(" ").strip
  output = tab+output if !tabbed[0].nil? and tabbed[0].strip.length < 1 and output.length > 0
  output
end

.strip_last_punctuation(text) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/easy_format.rb', line 52

def self.strip_last_punctuation(text)
  url = text
  ending = ""
  re = /([[:punct:]])$/
  if text =~ re
    md = re.match(text)
    url = md.pre_match
    ending = md[1]
    if ending == "/" #directory in URL
      url += ending
      ending = ""
    end
  end
  [url, ending]
end

.tabObject



2
3
4
# File 'lib/easy_format.rb', line 2

def self.tab
  '<span class="tab">&nbsp;</span>'
end