Class: RbbCode

Inherits:
Object
  • Object
show all
Defined in:
lib/rbbcode.rb,
lib/rbbcode/sanitize.rb,
lib/rbbcode/node_extensions.rb

Defined Under Namespace

Modules: Attributes, BlockquoteLineNode, BlockquoteNode, DocumentNode, ImgTagNode, ListItemNode, ListNode, LiteralTextNode, ParagraphNode, RecursiveConversion, SingleBreakNode, TagNode, URLTagNode, UTagNode

Constant Summary collapse

DEFAULT_SANITIZE_CONFIG =
{
  :elements => %w[a blockquote br code del em img li p pre strong ul u],
  :attributes => {
    'a'   => %w[href target],
    'img' => %w[alt src]
  },

  :protocols => {
    'a' => {'href' => ['ftp', 'http', 'https', 'mailto', :relative]}
  }
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RbbCode

Returns a new instance of RbbCode.



29
30
31
32
33
34
35
# File 'lib/rbbcode.rb', line 29

def initialize(options = {})
  @options = {
    :output_format => :html,
    :sanitize => true,
    :sanitize_config => RbbCode::DEFAULT_SANITIZE_CONFIG
  }.merge(options)
end

Class Method Details

.parser_classObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rbbcode.rb', line 12

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

Instance Method Details

#convert(bb_code) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rbbcode.rb', line 37

def convert(bb_code)
  # 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_#{@options[:output_format]}")
  if @options[:emoticons]
    output = convert_emoticons(output)
  end
  # Sanitization works for HTML only.

  if @options[:output_format] == :html and @options[:sanitize]
    Sanitize.clean(output, @options[:sanitize_config])
  else
    output
  end
end

#convert_emoticons(output) ⇒ Object



54
55
56
57
58
59
# File 'lib/rbbcode.rb', line 54

def convert_emoticons(output)
  @options[:emoticons].each do |emoticon, url|
    output.gsub!(emoticon, '<img src="' + url + '" alt="Emoticon"/>')
  end
  output
end

#output_formatObject



61
62
63
# File 'lib/rbbcode.rb', line 61

def output_format
  @options[:output_format]
end