-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrbbcode.rb
More file actions
73 lines (66 loc) · 2.03 KB
/
rbbcode.rb
File metadata and controls
73 lines (66 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Uncomment this when developing:
#$:.unshift './lib'
require 'erb'
require 'rubygems'
require 'treetop'
require 'sanitize'
require 'rbbcode/node_extensions'
require 'rbbcode/sanitize'
class RbbCode
def self.parser_class
if !instance_variable_defined?(:@grammar_loaded) or !@grammar_loaded
Treetop.load_from_string(
ERB.new(
File.read(
File.join(
File.dirname(__FILE__),
'rbbcode/rbbcode_grammar.treetop'
)
)
).result
)
@grammar_loaded = true
end
RbbCodeGrammarParser
end
def initialize(options = {})
@options = {
:output_format => :html,
:emoticons => false,
:sanitize => true,
:unsupported_features => :remove,
:sanitize_config => RbbCode::DEFAULT_SANITIZE_CONFIG
}.merge(options)
end
def convert(bb_code, options = {})
# Options passed to #convert will override any options passed to .new.
options = @options.merge(options)
output_format = options.delete(:output_format)
emoticons = options.delete(:emoticons)
sanitize = options.delete(:sanitize)
sanitize_config = options.delete(:sanitize_config)
# Collapse CRLFs to LFs. Then replace any solitary CRs with LFs.
bb_code = bb_code.gsub("\r\n", "\n").gsub("\r", "\n")
# Add linebreaks before and after so that paragraphs etc. can be recognized.
bb_code = "\n\n" + bb_code + "\n\n"
output = self.class.parser_class.new.parse(bb_code).send("to_#{output_format}", options)
if emoticons
output = convert_emoticons(output)
end
# Sanitization works for HTML only.
if output_format == :html and sanitize
Sanitize.clean(output, sanitize_config)
else
output
end
end
def convert_emoticons(output)
@options[:emoticons].each do |emoticon, url|
output.gsub!(emoticon, '<img src="' + url + '" alt="Emoticon"/>')
end
output
end
def output_format
@options[:output_format]
end
end