【问题标题】:Call Javascript from Rails 6 Service Object从 Rails 6 服务对象调用 Javascript
【发布时间】:2021-05-09 20:50:24
【问题描述】:

我想从服务对象调用 Javascript 库。

我在/app/javascript/packs/readability.js 中有以下 Javascript。

import Readability from '@mozilla/readability';

function articleBody(document) {
  var article = new Readability(document).parse();
  return article.content;
}

我发现 webpacker-ed 文件可以通过 asset_pack_path 在 Views 中使用。我尝试将其添加到我的服务对象中,如下所示(使用 therubyracer gem)。

(我尝试使用ExecJS,它似乎比 therubyracer 更受欢迎,但即使使用带有 ES5 Javascript 的未处理文件,它也只会返回错误。)

cxt = V8::Context.new
cxt.load(ActionController::Base.helpers.asset_pack_path 'readability.js')
puts cxt.eval("articleBody('http://example.com/')")

这是返回No such file or directory @ rb_sysopen - /packs/js/readability-20f57636.js。

localhost:3000/packs/js/readability-20f57636.js 在浏览器中加载正常。

如何在服务对象中加载经过 webpacker 处理的文件?

【问题讨论】:

    标签: ruby-on-rails webpack babeljs webpacker execjs


    【解决方案1】:

    错误是找不到文件,看起来您将其保存在 /javascript 但 webpacker 正在寻找 js。确保您的 webpacker.yml 中有这一行:

    default: &default
       source_path: app/javascript
    

    代替:

    default: &default
       source_path: app/js
    

    【讨论】:

    • 在我的 webpacker.yml 文件中我有你建议的:source_path: app/javascript。我猜编译会发送到 /js?
    • 有意思,可以发webpacker.yml吗?
    • 已添加到问题中。
    • 为什么不尝试添加一个js 文件夹并将其放入其中?
    • 我怎么知道 Webpacker 会调用什么文件?按照惯例,这些处理过的文件不会提交到 repo,因此生产服务器可能会为文件命名不同的名称。我开始认为这不是应该这样做的方式。当 Babel 编译的 Javascript 未在视图中使用时,也许有一种不同/更好的方式来使用它?
    【解决方案2】:

    如果 Javascript 不在浏览器中运行,则无需编译或转译 Javascript。您可以通过executing a shell script from Ruby 将数据从 Rails 发送到 Node。

    在服务对象(或控制器)中:

    require "open3"
    output, status = Open3.capture2("node ./lib/test.js", stdin_data: document)
    # The `output` variable above will be returned with the content of `data` from the below script.
    puts output
    

    /lib 或 /bin 中的脚本:

    const fs = require('fs');
    
    fs.readFile(0, 'utf8', function(err, data) {
      if (err) throw err;
      // do your proccessing here...
      console.log(data);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 2013-10-18
      • 2017-02-25
      • 2020-08-20
      • 2012-02-27
      • 2012-03-16
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多