在 Volt 框架中使用 ruby 类

Use ruby classes in Volt Framework

我想知道在 Volt 框架中包含 ruby 类 的最佳方法是什么。我想使用 Socket Class 来查找站点访问者的 IP 地址。我想在控制器中使用它,但是放置:

require 'socket'

文件顶部的内容不起作用。有什么建议吗?

嗯,我认为您不能在客户端使用 Socket class,因为 Volt 使用 OpalRb to run Ruby on the client, and unfortunately I don't think Opal can support the Socket class since that's kind of hard to do in the browser. You can, however, run code on the server side and pass your desired results on to the client. You can do so using Volt's tasks。您可以像这样创建它们:

require 'socket'

class SocketTask < Volt::Task
  def use_sockets
    # do your thing with sockets here...
  end
end

然后您可以在其他地方使用它们,例如,在这样的控制器中:

class Controller < Volt::ModelController
  def some_action
    SocketTask.use_sockets

    # You can also use the #then method of the returned promise to get the result of the call.
    # You can even use the #fail method on the promise to get any thrown errors.
    # The following can also run code on the client.

    SocketTask.use_sockets.then do |result|
      alert result
    end.fail do |error|
      puts error
    end
  end
end

Rick Carlino 也有一个关于 Volt 任务的精彩截屏视频 here