Class: DText

Inherits:
Object
  • Object
show all
Defined in:
lib/dtext.rb,
lib/dtext/version.rb,
ext/dtext/rb_dtext.cpp

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"2.0.6"

Class Method Summary collapse

Class Method Details

.c_parse(input, f_inline, f_allow_color, f_max_thumbs, base_url) ⇒ Object



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
# File 'ext/dtext/rb_dtext.cpp', line 9

static VALUE c_parse(VALUE self, VALUE input, VALUE f_inline, VALUE f_allow_color, VALUE f_max_thumbs, VALUE base_url) {
  if (NIL_P(input)) {
    return Qnil;
  }

  StringValue(input);

  DTextOptions options = {};
  options.f_inline = RTEST(f_inline);
  options.allow_color = RTEST(f_allow_color);
  options.max_thumbs = FIX2LONG(f_max_thumbs);

  if (!NIL_P(base_url)) {
    options.base_url = StringValueCStr(base_url); // base_url.to_str # raises ArgumentError if base_url contains null bytes.
  }

  if (memchr(RSTRING_PTR(input), 0, RSTRING_LEN(input))) {
    rb_raise(cDTextError, "invalid byte sequence in UTF-8");
  }

  try {
    std::string_view dtext(RSTRING_PTR(input), RSTRING_LEN(input));
    auto result = StateMachine::parse_dtext(dtext, options);

    VALUE retStr = rb_utf8_str_new(result.dtext.c_str(), result.dtext.size());
    VALUE retPostIds = rb_ary_new_capa(result.posts.size());

    for (long post_id : result.posts) {
      rb_ary_push(retPostIds, LONG2FIX(post_id));
    }

    VALUE ret = rb_ary_new_capa(2);
    rb_ary_push(ret, retStr);
    rb_ary_push(ret, retPostIds);

    return ret;
  } catch (std::exception& e) {
    rb_raise(cDTextError, "%s", e.what());
  }
}

.parse(str, inline: false, allow_color: false, max_thumbs: 25, base_url: nil) ⇒ Object

Raises:

  • (TypeError)


7
8
9
10
11
12
# File 'lib/dtext.rb', line 7

def self.parse(str, inline: false, allow_color: false, max_thumbs: 25, base_url: nil)
  return nil if str.nil?
  raise TypeError unless str.respond_to?(:gsub)
  str = preprocess_for_tables(str)
  c_parse(str, inline, allow_color, max_thumbs, base_url)
end

.preprocess_for_tables(str) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/dtext.rb', line 16

def self.preprocess_for_tables(str)
  str.gsub(/(?:\[ltable\])(.*?)(?:\[\/ltable\]|\z)/mi) do
    contents = Regexp.last_match[1].strip
    row_num = 0
    rows = contents.split(/\n/).map do |row|
      cols = row.split(/(?<!\\)\|/).map do |col|
        row_num == 0 ? "[th]#{col}[/th]" : "[td]#{col}[/td]"
      end
      new_row = row_num == 0 ? "[thead][tr]#{cols.join('')}[/tr][/thead][tbody]" : "[tr]#{cols.join('')}[/tr]"
      row_num += 1
      new_row
    end
    "[table]#{rows.join('')}[/tbody][/table]"
  end
rescue ArgumentError => e
  raise Error.new(e.message)
end