将 Ruby 扩展编译为 JavaScript
在本页中,您将学习如何使用 Opal 将用 Ruby 编写的 Asciidoctor 扩展编译为 JavaScript。
这是一种高级技术,具有一定的限制。推荐的方式是直接用 JavaScript 编写扩展,以便在 Asciidoctor.js 中使用。 |
在警告之后,假设您想在基于 JavaScript 的应用程序中使用以下 Asciidoctor 扩展(用 Ruby 编写)。
lib/tel-inline-macro.rb
# An inline macro that turns URIs with the tel: URI scheme into links.
#
# Usage
#
# tel:1-800-555-1212[]
#
Asciidoctor::Extensions.register do
inline_macro do
named :tel
parse_content_as :text
process do |parent, target, attrs|
if (text = attrs['text']).empty?
text = target
end
target = %(tel:#{target})
(create_anchor parent, text, type: :link, target: target)
end
end
end
编译
要编译这个扩展,您需要安装 opal-compiler
包:
npm install opal-compiler
安装这个包之后,您可以编写以下 Node 脚本来编译扩展:
compile.js
const fs = require('fs')
const Builder = require('opal-compiler').Builder
// Opal object will be available on the global scope
const builder = Builder.create()
builder.appendPaths('lib') (1)
const result = builder.build('tel-inline-macro.rb') (2)
fs.writeFileSync('tel-inline-macro.js', result.toString(), 'utf8') (3)
1 | 扩展文件位于 lib 目录中 |
2 | 扩展文件名为 tel-inline-macro.rb |
3 | 将会写入一个名为 tel-inline-macro.js 的文件 |
然后运行它:
node compile.js
上述命令将创建一个名为 tel-inline-macro.js 的文件,里面包含编译后的 JavaScript 扩展代码。
使用
在前一部分中,我们展示了如何将 Ruby 扩展编译为 JavaScript。在本部分中,我们将使用这个扩展。
创建一个简单的文档:
document.adoc
= Contacts
== Professional
Guillaume Grossetie tel:1-800-555-1212[]
接着创建一个 Node 脚本来转换这个文档:
convert.js
const asciidoctor = require('asciidoctor')()
require('./tel-inline-macro.js') (1)
const html = asciidoctor.convertFile('document.adoc', { 'to_file': false }) (2)
console.log(html)
1 | 加载本地扩展 tel-inline-macro.js。 |
2 | 将文档与启用的 tel 内联宏扩展一起转换。 |
确保已安装 Asciidoctor.js: |
然后运行:
node convert.js
<div class="sect1">
<h2 id="_professional">Professional</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Guillaume Grossetie <a href="tel:1-800-555-1212">1-800-555-1212</a></p> (1)
</div>
</div>
</div>
1 | tel 宏已被转换为一个链接。 |