代码段格式化脚本 - mindpin/knowledge-space-net-lib GitHub Wiki

一段脚本,用于处理代码文本后,生成供 Richcodetextview 使用的格式化信息。
此脚本为 Ruby 脚本,依赖 CodeRay 库。

脚本内容如下:

require 'coderay'
require 'json'

class QuestionCodeFormatter
  def initialize(code_text, lang)
    @code_text = code_text
    @lang = lang

    @scan = CodeRay.scan(@code_text, @lang)
  end

  def get_content
    json = JSON.parse @scan.json
    block = []
    arr = []

    json.each { |x|
      type = x['type']
      kind = x['kind']
      text = x['text']
      action = x['action']

      case type
      when 'text'
        arr << [kind, text, block.last].compact
      when 'block'
        case action
        when 'open'
          block << kind
        when 'close'
          block.pop
        end
      end
    }

    return arr
  end
end

使用示例如下:

code_text = File.open(code_file_path).read
formatter = QuestionCodeFormatter.new code_text, lang
formatted_content = formatter.get_content

在 Server 端,实现

question.make_content

时,应调用此脚本逻辑以包装代码段部分。具体参考 问题正文标准JSON格式

⚠️ **GitHub.com Fallback** ⚠️